1

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?

1
  • JSON.parse(string) Commented Aug 9, 2016 at 7:27

4 Answers 4

7

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, '"$&"'))
)

Sign up to request clarification or add additional context in comments.

3 Comments

Would you mind explaining how (/\d+/g, '"$&"') is functioning?
@JayGould \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/…)
@JayGould : glad to help :)
2

From this answer https://stackoverflow.com/a/13272437/5349462 you should use

var array = JSON.parse(string);

Comments

0

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

0

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

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
@Panos : Kindly Check the solution for your scenario and validate the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.