Jean Dupont Jean Dupont - 3 months ago 8
Javascript Question

Convert special String to an Array Javascript

I have strings like this :

var S1 = "[ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\" ]";
var S2 = "[ \"2\" ]";
var S3 = "[ \"1\", \"2\", \"3\" ]";


And I want to convert them under JavaScript to an Array like this :

var S1a = ['1','2','3','4','5','6','7'];
var S2a = ['2'];
var S3a = ['1','2','3'];


Please how can I achieve the above ?

Answer

You can use JSON.parse() for this

Write your code as follow:

var S1 = "[ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\" ]";
var arr = JSON.parse(S1);

From this post