Parsing Javascript Array - javascript

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);

Related

How to get the index of a string in google docs using google App Script

I want to search for a string and then replace it with an image on google docs. For that, I want to get the index of the string and then replace it with an image. But I'm unable to get the index of the string so far.
Below is a snippet of what I am doing:
var element = '<<19>>';
options = {muteHttpExceptions: true};
var resp = UrlFetchApp.fetch(mylist[x-1], options);
var image = resp.getBlob();
//getting the index of element and then replacing it with image
var rangeElement = body.findText(element);
var foundElement = rangeElement.getStartOffset();
body.replaceText(element, body.insertImage(foundElement, image));
I've tried using findText(searchPattern) but it didn't work as it returns a range element and I'm getting output as 0 everytime.
This is how you find text on your document and replace it with an image:
function findAndReplaceWithImage() {
var element = "<<19>>";
var doc = DocumentApp.getActiveDocument().getBody();
var image = "your image url";
var blob = UrlFetchApp.fetch(image).getBlob();
var paragraphs = doc.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
if (text === element) {
//Found your match
doc.removeChild(paragraphs[i]);
doc.insertImage(i, blob);
}
}
}
Hope this helps!

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]

Access XML Attribute Names in Extendscript

I'm trying to parse an xml Object in extendscript and especially deal with the Attributes. I know i can access xml attributes by
xmlObj.#attributename
and
xmlObj.attributes()
returns a list of all attributes, but I also need the attribute names not just the values. Is there anyway to get something like and associative array/object with names and values?
(I use extendscript for illustrator CS6)
thank you,
arno
The code below should get you going. Take also a look into the XMLElement Object.
var main = function() {
// create some xml and write it to file
var root = new XML("<root/>");
var child = new XML("<child/>");
child.#string = "Hello Attribute"; // jshint ignore:line
child.#num = 23; // jshint ignore:line
root.appendChild(child);
var file = new File("~/Desktop/test.xml");
var xml = root.toXMLString();
file.open("W");
file.write(xml);
file.close();
// get the current doc
var doc = app.activeDocument;
// import the xml
doc.importXML(file);
// get the elements
var xmlroot = doc.xmlElements[0];
var xmlchild = xmlroot.xmlElements[0];
// loop all attributes of element "child"
// and write them into the console
for (var i = 0; i < xmlchild.xmlAttributes.length; i++) {
var attr = xmlchild.xmlAttributes[i];
$.writeln(attr.name);
}
};
main();
i've found a way solve it with regular Expressions
function getAttributes(xml_node_str) {
// select the start tag <elem >
var reg_exp = /<[^>]*>/;
var start_tag_str = reg_exp.exec(xml_node_str);
// extract the attributes
reg_exp = /[^"\s]*="[^"]*"/g;
var result;
var attributes = [];
while ((result = reg_exp.exec(start_tag_str)) !== null) {
// the attribute (name="value")
var attr = result[0];
// array containing name and "value"
var attr_arr = attr.split('=');
// delete the "'s
attr_arr[1] = attr_arr[1].substr(1, attr_arr[1].length - 2);
attributes.push(attr_arr);
}
return attributes;
}
I still parse the xml with Extendscripts/Illustrators xml-class and then extract the attributes manually
var xml = <root><obj a1="01" a2="02" ></obj></root > ;
var attributes = getAttributes(xml.obj.toXMLString());
for (var i = 0; i < attributes.length; i++) {
alert(attributes[i][0] + ' -> ' + attributes[i][1]);
}

How to build 2 dimensional array from a string of options for a select tag in Javascript?

In Javascript, I have a string of options for a select tag. This is my string:
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>';
In Javascript, I want to convert it to a 2-dimensional Array where 1st dimension will store the id and 2nd dimension will store the text of an option.
How can I do that? I am looking for Javascript solution; I am open to 3rd party solutions also like jQuery.
You can do it by converting the string into DOM options, then iterating over them, so:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsAsArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsAsArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
You can also do it by parsing the string, but that may be more work.
Edit
You can also use the new DOMParser, but fairly recent browsers are required for support:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
The above creates an array of:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
if you want pairs like:
[[id0, text0], [id1, text1], ...]
Then the above can be:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
which can be reduced to:
function optionsAsArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}
I have used jQuery for the solutions below.
If you want the array to be made from DOM then you can do this
<select id="selectopt"><option id="">Select</option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option></select>
var arr = [];
console.log('====array 1===');
$('select option').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
arr.push([id, value]);
console.log(arr);
});
If you need it to be made using the string then use $.parseHTML for converting the string to DOM nodes.
var arr2 = [];
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option>';
var options = $.parseHTML(myOptionsString);
console.log('====array 2===');
for (var i=0; i< options.length; i++){
var id1 = options[i].id;
var value1 = options[i].value;
arr2.push([id1, value1]);
console.log(arr2);
}
Fiddle Demo

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

Categories

Resources