I have a string with the given value:
var string = "[[1,2],[3,4],[5,6],[7,8]]";
I would like to know how can I convert this text to an array. Not only that but i would like also [1,2], [3,4] etc. to be arrays as well. Does anyone know how I can accomplish that?
-
JSON.parse(string)maioman– maioman2016年08月09日 07:27:21 +00:00Commented Aug 9, 2016 at 7:27
4 Answers 4
Since it's a valid JSON you can make it to number array by parsing it using JSON.parse method.
var string = "[[1,2],[3,4],[5,6],[7,8]]";
console.log(
JSON.parse(string)
)
To convert to a string array you need to wrap number with " (quotes) to make string in JSON use String#replace method for that.
var string = "[[1,2],[3,4],[5,6],[7,8]]";
console.log(
// get all number and wrap it with quotes("")
JSON.parse(string.replace(/\d+/g, '"$&"'))
)
3 Comments
(/\d+/g, '"$&"') is functioning?\d+ matches digits and g is for global match....... and replacing it with quoted digit...... ('"$&"' - here $& is the matched string ---- for more info refer developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)From this answer https://stackoverflow.com/a/13272437/5349462 you should use
var array = JSON.parse(string);
Comments
JSON.parse() function can help you:
var string = "[[1,2],[3,4],[5,6],[7,8]]";
var array = JSON.parse(string);
JSON.parse() is supported by most modern web browsers (see: Browser-native JSON support (window.JSON))
Comments
You can use the below code to convert String to array using javascript. You simple use JSON.parse method to convert string to json object. As our specified string has two-dimensional array,we need to do operation on json object to get required format.
var string = "[[1,2],[3,4],[5,6],[7,8]]";
//parses a string as JSON
var obj=JSON.parse(string);
console.log(obj);