Create 2d array from string - javascript
I have the following string :
[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],]
How can I create a 2d array of strings from it ?
EDIT
I've removed html tags since they're not the problem here. Also I'd like to do it without using any additional libs to keep it lightweight.
Except from the HTML tags in it, it would be valid JSON. You could remove the HTML tags and parse it using any library that handles JSON, like jQuery:
var arr = $.parseJSON(theString.replace(/<br\/>/g,''));
It would also be valid Javascript code with the HTML tags removed, so if you have full control over where the string comes from so that you are certain that it can never contain any harmful code, you could use the eval function to execute the string:
// Warning: 'eval' is subject to code injection vulnerabilities
var arr = eval(theString.replace(/<br\/>/g,''));
You will need to remove the <br/> from the string. Then you should be able to do:
var my2darray = eval(mystring);
Related
apple .replace() Html element generate by handlebar js
I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements. For instance i have this role of p tag which display a row of data by handlebar js: <p id="pre-region">{{region}}</p> and the result of it is 1,44 and i 'd like to change it to 1+44 If you haven't had any experience of handlebar js then consider the tag be <p id="pre-region">1,44</p> how should i change from 1,44 to 1 +44? UPDATE 1 Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax. After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error. MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4 This is how may API looks like at the moment MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1+4 should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>: <script> var node = document.getElementById('pre-region'); node.innerHTML = node.innerHTML.replace(',', '+'); </script> I'll check out the handlebars js in case it does not work. Update: As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring): decodeURIComponent('1%2B44'); // you get '1+44' Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page. Update 1 You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is: MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4 What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language. Update 2 The solution above only replace the first occasion of comma to +. To solve that, simply use: <script> var node = document.getElementById('pre-region'); node.innerHTML = node.innerHTML.replace(/,/g, '+'); // Regular Expression is used here, 'g' for global search. </script> PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want: <script> String.prototype.replaceAll = function(search, replacement) { var target = this; return target.split(search).join(replacement); } // Another method to replace all occasions using `split` and `join`. </script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go: You could try this code in another js file that runs after handlebars: var pre = $('#pre-region'); // defines a variabe for the element (same as // document.getElementById('pre-region')) var retrievedRegion = pre.innerHTML; var splitten = retrievedRegion.split(','); var concatenated = parseInt(split[0]) + parseInt(split[1]) retrievedRegion.innerHTML = "'" + concatenated) + "'"; or using replace(): retrievedRegion.replace(',','+')
HTML5 data-attributes : How to modify array of data attached to DOM element?
I try to modify some HTML5 data-attribute with jquery. I know how to do when it is simple like this : <div id="element" data-options="HelloWorld"></div> //Modify with jQuery : $("#element").data("options","Bye Bye"); But in my case, i would like to modify a more complexe data-options (it's a joomla module). data-options is organized like this with an array of datas : data-options="{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}" How can i select and modify only icon for example ?
You can use the function overload of jQuery.fn.data $('#element').data('options', function(data){ var obj = JSON.parse(data); obj.forEach(function(o){ o.icon = "some other color"; }); return JSON.stringify(obj); }); The above works assuming you have the following as your data. '[{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}]' To properly declare the json, you can put 'em in '' instead of "" which will save you from the headache of escaping double quotes.
From comment: You will simply need to convert it from a string to an object using JSON parsing. The double-quotes are going to cause you grief though. var values = $.parseJSON($('#element').data('options')); One only way to include a JSON literal in a standard HTML attribute is by encoding the "'s to "s which is pretty horrible: e.g. data-options=";{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}"; or you can use single quotes for the delimiting (while not standard this will work on most browsers): data-options='{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"red","popup":1},{"title":"Test","lat":"48.6069129","lng":"7.7612831","icon":"blue","popup":2}'
Javascript - search for HTML elements in string
I have string with html elements. There are tables with captions. I need to find table which has caption with certain text and then return this table - as a string. What is the best way to do this with simple javascript, without any libraries ? F.e. this is an initial string <table border="1"><caption><strong>First</strong></caption><tbody><tr><td>...</td></tr></tbody></table><table border="1"><caption><strong>Result</strong></caption><tbody><tr><td>...</td></tr></tbody></table><table border="1"><caption><strong>Last</strong></caption><tbody><tr><td>...</td></tr></tbody></table> I want to get this string : <table border="1"><caption><strong>Result</strong></caption><tbody><tr><td></td></tr></tbody></table> Any advice or algorithm how to effeciently resolve this problem ? The challenge is to resolve it with javascript without using any third-party libraries and also without converting text into xml or something similar (because some of html code is not well formatted and it causes errors).
I have not had time to completely test this, but you might be able to try using a regular expression and the match() function. Assuming your table string is in a variable called str, then something along the lines of var res = str.match(\b<table\.\w+_</table>\b); res will be an array of matches of strings that begin with '', which you could then check to see which string contains the caption that you need. Hope that helps!
Unable to remove html tags from response JSON
Hi I am new to AngularJS. I am having a problem parsing JSON data to proper format. Actually the JSON response itself returned HTML format data (it contains HTML tags like <,;BR,> etc). If I check the response in browser it returns fine, but in device(TAB,MOBILE) the HTML tags are also getting appended. I am using AngularJS to bind the JSON response to DOM. Is there any way to simply ignore HTML tags in JQuery or in AngularJs? At the same time I don't want to remove the HTML tags as they are necessary to define "new line", "space", "table tag" etc. A sample response I am getting is like: A heavier weight, stretchy, wrinkle resistant fabric.<BR><BR>Fabric Content:<BR>100% Polyester<BR><BR>Wash Care:<BR> If I apply the binding using {{pdp.desc}}, the HTML tags are also getting added. Is there any way to accomplish this? I have added ng-bind-html-unsafe="pdp.desc", but still "BR" tags r coming.
useless html tags can be remove using regix expression, try this str.replace(/<\/?[^>]+>/gi, '')
Try to use three pairs of brackets {{{pdp.desc}}} In Handlebars it works, possible in your case to.
Use JS HTML parser var pattern = #"<(img|a)[^>]*>(?<content>[^<]*)<"; var regex = new Regex(pattern); var m = regex.Match(sSummary); if ( m.Success ) { sResult = m.Groups["content"].Value; courtesy stackoverflow.
Getting jQuery to work with another library (XML parsing)
We are using jQuery to generate an XML fragment and then convert it to a string using the html() function. But as we just found out, and if anyone doesn't know, the html() JavaScript function as implemented in IE is broken, broken, broken. Basically, it capitalizes some tags, adds attributes to others "helpfully" (in our case, ), and generally doesn't do the Right Thing. I would like to use something like this to generate the XML string instead: http://www.stainlessvision.com/jquery-html-vs-innerxhtml However, this library won't play nicely with jQuery out of the box, e.g.: var $dummyRoot = $('<dummyroot/>'); // since html() doesn't generate the outer element var $foo = $('<foo></foo>'); var $font = $('<font ></font >'); $foo.append($font); $dummyRoot.append($foo); var $s = innerXHTML($dummyRoot); // <-- Doesn't work I think it wants a more W3C DOM-ish object. How can I get jQuery to talk to this innerXHTML() function; or, alternatively, is there another function I can use (maybe something built into jQuery or a jQuery plugin))? Edit: Follow up for DDaviesBrackett's question. I also have a "body" element in my XML; look how it picks up CSS styling (and not just a element). Is there an unwritten rule to not generate XML inside the DOM whose elements have names like body, font, head, etc.? var $dummyRoot = $('<dummyroot/>'); var $foo = $('<foo></foo>'); var $body = $('<body></body>'); var $font = $('<font></font>'); $body.append($font); $foo.append($body); $dummyRoot.append($foo); var $s = innerXHTML($dummyRoot[0]); // $s equals "<foo><body bottommargin="15" leftmargin="10" rightmargin="10" topmargin="15"><font size="+0"></font></body></foo>"
the jQuery object wraps its contents, but exposes them via an array indexer. What do you get when you use var $s = innerXHTML($dummyRoot[0]); instead of your example?
Is there an unwritten rule to not generate XML inside the DOM whose elements have names like body, font, head, etc.? jQuery relies on the innerHTML property to parse a given piece of text and construct the DOM from that. It was never meant to parse or generate XML as colliding names can give totally unpredictable results depending on how the browser sees it. See jQuery won’t parse xml with nodes called option How do I parse xml with jQuery? Parse content like XML, with jQuery I have given a similar answer for generating proper XML in fewer steps using a recursive approach. To create the following XML: <foo> <body> <font></font> </body> </foo> you would write: Σ('foo', Σ('body', Σ('font', '') ) ); Σ just looks cooler, but you can change the function name to whatever you want :)