Panos Panos - 1 month ago 7
Javascript Question

String to JavaScript array with elements as arrays

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?

Answer

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

Comments