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?

Nhan
  • 3,595
  • 6
  • 30
  • 38

4 Answers4

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, '"$&"'))
)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Would you mind explaining how `(/\d+/g, '"$&"')` is functioning? – James Gould Aug 09 '16 at 07:50
  • 1
    @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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter) – Pranav C Balan Aug 09 '16 at 07:52
  • @JayGould : glad to help :) – Pranav C Balan Aug 09 '16 at 07:53
2

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

var array = JSON.parse(string);
Community
  • 1
  • 1
Bardock
  • 65
  • 7
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))

Community
  • 1
  • 1
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);
Asmi
  • 651
  • 1
  • 8
  • 16
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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! – Blue Aug 09 '16 at 23:55
  • @Panos : Kindly Check the solution for your scenario and validate the answer. – Asmi Aug 10 '16 at 11:42