Jquery finding patterns in string - javascript

I need to find path information from a string using jquery and push the results into an array.
The string output looks like;
"var rsr = Raphael('rsr', '270', '266');
var path_a = rsr.path('M144.869,199c0,7.659-5.479,13.139-13.14,
13.139 c-7.659,0-14.598-5.479-14.598-13.139s6.209-13.139,13.869-
13.139S144.869,191.341,144.869,199z'); path_a.attr({fill: 'non .... etc"
I need to retrieve every occurrence of the path information with in rsr.path() ;
How would i go about achieving this? using $.each on my string with a regex?
thanks cam

JavaScript will let you do this with a regular expression:
var s = " var rsr = Raphael('rsr', '270', '266'); var path_a = rsr.path('M144.869,199c0,7.659-5.479,13.139-13.14, 13.139 c-7.659,0-14.598-5.479-14.598-13.139s6.209-13.139,13.869- 13.139S144.869,191.341,144.869,199z'); path_a.attr({fill: 'non .... etc";
var regex = /M144\.869(.+?)869,199z/g;
var matches = regex.exec(s);
matches[0] then contains the capture group.

i found this worked..
$(document).ready(function(){
$('form.svg-convert').submit(function(event){
var content = $(this).find('textarea').val();
process(content);
event.preventDefault();
})
})
var process = function(c){
var content = c,
paths = [];
var contentSplit = content.split('path(');
contentSplit.shift();
$.each(contentSplit,function(i,v){
var path = v.split(')');
path = path[0];
paths.push(path);
});
}

Related

How to split Javascript code (bs4) using Python

So I have been having some issues when trying to scrape Javascript values from a bs4 code.
Basically the javascript looks like
<script type="text/javascript">
var FancyboxI18nClose = 'Close';
var FancyboxI18nNext = 'Next';
var FancyboxI18nPrev = 'Previous';
var PS_CATALOG_MODE = false;
var ajaxsearch = true;
var attribute_anchor_separator = '-';
var blocksearch_type = 'top';
var combinationsFromController = {"163972":{"attributes_values":{"15":"40"},"attributes":[75],"price":0,"specific_price":false,"ecotax":0,"weight":0.6,"quantity":1,"reference":"IDP20059--IDPA163972","unit_impact":0,"minimal_quantity":"1","date_formatted":"","available_date":"","id_image":-1,"list":"'75'"}};
var comparator_max_item = 0;
</script>
and what I am trying to do here is to scrape the value var combinationsFromController = however what I tried to do is:
bs4 = soup(requests.text, 'html.parser')
for nosto_sku_tag in bs4.find_all('script', {'type': 'text/javascript'}):
if 'combinationsFromController' in nosto_sku_tag.text.strip():
print(nosto_sku_tag)
for att, values in json.loads(
re.findall('var combinationsFromController = (\{.*}?);', nosto_sku_tag.text.strip())[0][:-1]).values():
print(values)
Which gives me an error of Expecting ',' delimiter: line 1 column 4112 (char 4111)
I did realized that whenever I try to do
for nosto_sku_tag in bs4.find_all('script', {'type': 'text/javascript'}):
if 'combinationsFromController' in nosto_sku_tag.text.strip():
print(nosto_sku_tag)
print("---------")
The outprint gives me:
var FancyboxI18nClose = 'Close';
var FancyboxI18nNext = 'Next';
var FancyboxI18nPrev = 'Previous';
var PS_CATALOG_MODE = false;
var ajaxsearch = true;
var attribute_anchor_separator = '-';
var blocksearch_type = 'top';
var combinationsFromController = {"163972":{"attributes_values":{"15":"40"},"attributes":[75],"price":0,"specific_price":false,"ecotax":0,"weight":0.6,"quantity":1,"reference":"IDP20059--IDPA163972","unit_impact":0,"minimal_quantity":"1","date_formatted":"","available_date":"","id_image":-1,"list":"'75'"}};
var comparator_max_item = 0;
----------------------------
Which seems to mean that the javascript code is as one code which I believe maybe needs to split, However I tried to use regex for it but it didn't help me.
So my question is how am I able to scrape ONLY the value var combinationsFromController =?
Use the following regex pattern to isolate the entire javascript object which is assigned to that variable.
combinationsFromController = (.*?);
Try it here.
E.g.
import requests, re, json
r = requests.get(url)
p = re.compile(r'combinationsFromController = (.*?);', re.DOTALL)
data = json.loads(p.findall(r.text)[0])

JQuery: How to change colors dynamically?

I'm using jumble.js to jumble colors of text, but finding difficulty in dynamically setting the colors from user input.
User selects colors using the spectrum.js color palette. I'm able to strip the rbg from rbg(xxx,xx,xx); to xxx,xx,xx. but unable to pass that into the jumble call method.
here is my code.
$(document).on('click', '#cypher-branding-jumble-text', function () {
var colour1 = $("#cypher-branding-jumble-colour1").spectrum("get");
var colour2 = $("#cypher-branding-jumble-colour2").spectrum("get");
colour1 = colour1.toRgbString();
colour1 = colour1.replace('rgb(', '');
colour1 = colour1.replace(')', '');
colour1 = colour1.replace(' ', '');
colour2 = colour2.toRgbString();
colour2 = colour2.replace('rgb(', '');
colour2 = colour2.replace(')', '');
colour2 = colour2.replace(' ', '');
var colour_1 = [colour1];
var colour_2 = [colour2];
$('#cypher-branding-main-edit-right-txt-text').jumble(colour_1,colour_2,true,false);
});
Jumble plugin > https://github.com/vonKristoff/jumble
If I read the Spectrum API correctly, this should work with less string nonsense. And I was able to verify on the Spectrum website that the 'get' call can use toRgb().
$(document).on('click', '#cypher-branding-jumble-text', function () {
var colour1 = $("#cypher-branding-jumble-colour1").spectrum("get").toRgb();
var colour2 = $("#cypher-branding-jumble-colour2").spectrum("get").toRgb();
$('#cypher-branding-main-edit-right-txt-text')
.jumble([colour1.r-0,colour1.g-0,colour1.b-0],[colour2.r-0,colour2.g-0,colour2.b-0],true,false);
});
Why is there a document listener for #cypher-branding-jumble-text, shouldent it just be $('#cypher-branding-jumble-text').click(...)?
this line has to be changed as color_1 = a.split(",") so it will really split into three values and create array. Same for color_2 also.
Nagappan's comment solved my issue very nicely.
Was meant to split the string. Modified code as below.
$(document).on('click', '#cypher-branding-jumble-text', function () {
var colour1 = $("#cypher-branding-jumble-colour1").spectrum("get");
var colour2 = $("#cypher-branding-jumble-colour2").spectrum("get");
colour1 = colour1.toRgbString();
colour1 = colour1.replace('rgb(', '');
colour1 = colour1.replace(')', '');
colour1 = colour1.replace(' ', '');
colour2 = colour2.toRgbString();
colour2 = colour2.replace('rgb(', '');
colour2 = colour2.replace(')', '');
colour2 = colour2.replace(' ', '');
//modified lines using split
var colour_1 = colour1.split(",");
var colour_2 = colour2.split(",");
$('#cypher-branding-main-edit-right-txt-text').jumble(colour_1,colour_2,true,false);
});

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Parsing Javascript Array

I have an array as a attribute on a link.
Here is the array
images="["one.jpg","two.jpg"]"
How would I parse through this array and have it read back to me one.jpg,two.jpg?
This is what I am doing now and it is giving me an error back. I don't believe json parsing is whats needed here.
var imgs = $("#"+number).attr("images");
var imgList = jQuery.parseJSON(imgs);
EDIT: ACTUAL CODE
var number = $(this).attr("data-id");
var url = $("#"+number).attr("url");
$(".portfolio-url").html("<h3 class='pacifico'>url</h3><p><a href='http://"+url+"' target='_blank'>"+url+"</a></p>");
var cli = $("#"+number).attr("client");
$(".portfolio-client").html("<h3 class='pacifico'>client</h3><p>"+cli+"</p>");
var pgs = $("#"+number).attr("pages");
pgs = pgs.replace(/\[/g,"");
pgs = pgs.replace(/\]/g,"");
pgs = pgs.replace(/\"/g,"");
var pages = new Array();
pages = pgs.split(",");
var img = $("#"+number).attr("images");
img = img.replace(/\{/g,"");
img = img.replace(/\}/g,"");
img = img.replace(/\"/g,"");
var images = new Array();
images = img.split(",");
var portSkills = "<h3 class='pacifico'>skills</h2>";
portSkills += "<p>";
for (i=0;i<pages.length;i++) {
if (pages[i] != "Clients") {
var finalPage = "";
for (j=0;j<pages[i].length;j++)
{
var ch = pages[i].charAt(j);
if (ch == ch.toUpperCase()) {
finalPage += " ";
}
finalPage += pages[i].charAt(j);
}
portSkills += finalPage+"<br />";
}
}
portSkills += "</p>";
$(".portfolio-skills").html(portSkills);
var imgs = $("#"+number).attr("images");
var imgList = jQuery.parseJSON(imgs);
Basically, its looping through parameters
I'd encourage you to modify your attribute-value format to something along these lines:
<div id="one" data-images="file1.jpg,file2.jpg">Foo, Bar</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Note here I'm using a valid data- attribute, and the value of this attribute is just a list of comma-separated filenames. No need to place [ or ] in this value in order to get an array.
Now, to get your array:
var images = $("#one").data("images").split(",");
Which results in the following array:
["file1.jpg", "file2.jpg"]
Don't put that kind of string in the attribute, you could just put a comma separated string instead. (And you could use data attribute.)
For example:
<a id="foo" data-images="one.jpg,two.jpg">foo</a>
then you could get it by:
var imgList = $('#foo').data('images').split(',');
for (var i = 0; i < images.length; i++) {
var image = images[i];
}
For starters:
images = ["one.jpg", "two.jpg"]; is an array, yours is invalid.
to have it read back to you
for(image in images)
console.log(images[image]);
or the jQuery way
$.each(images, function(index){
console.log(images[index]);
});
if its a String that you need to split
then but that is of course if the string looks like this
var img = '["one.jpg", "two.jpg"]';
var images = img.replace(/\[|\]|"| /g,'').split(',');
this will give you an array parsed from a string that looks like an array.
Give the join() method a try:
images.join();
=> "one.jpg,two.jpg"
images.join(", ");
=> "one.jpg, two.jpg"
Edit: To declare your Array:
var images = ["img1", "img2", "img3"];
or
var images = new Array("img1", "img2", "img3");
Then you can use the join() method, and if that still doesn't work, try the following:
// should be true, if not then you don't have an Array
var isArray = (images instanceof Array);

Categories

Resources