-3

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 ?

Jean Dupont
  • 177
  • 1
  • 13

3 Answers3

3

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

Community
  • 1
  • 1
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37
1

Just for fun you can also do l like this. If you want the resulting array to contain integers instead of string characters then just do r.concat(+e) instead of r.concat(e)

var s = "[ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\" ]",
    a = s.split(/\[*\s*\"(\d+)\",*\s*\]*/).reduce((r,e,i) => i%2 ? r.concat(e) : r,[]);
console.log(a);
Redu
  • 25,060
  • 6
  • 56
  • 76
0

You can JSON parse like :

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

output will be : ["1", "2", "3", "4", "5", "6", "7"]

Example Fiddle: https://jsfiddle.net/us9L1ed0/

JSON.parse Reference : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse http://www.w3schools.com/json/json_eval.asp

Code Snippet as per your example

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

var S1a =JSON.parse(S1)
var S2a=JSON.parse(S2)
var S3a = JSON.parse(S3)

console.log(S1a);
console.log(S2a);
console.log(S3a);
Venkat
  • 2,549
  • 2
  • 28
  • 61