Tahmid Khan Nafee Tahmid Khan Nafee - 1 month ago 7x
JSON Question

Converting a structured string to an array using Javascript

Lets say I have a string like so:

var myStr = "[1,2,3,4,5]";

How can I convert it to something like this:

[1, 2, 3, 4, 5]

I'm trying to do this using the following command:


However, I get an error. What's the right way to do this?
Moreover, can the same method be used for structured strings containing non-numbers? Like the following:

var myStr2 = "[cats, dogs, elephants]"


To be specific, I get this error:

SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 5 of the JSON data

The string part is something like this:

[16 Sep,16 Sep,16 Sep,16 Sep,16 Sep,16 Sep,16 Sep]

So I dont really understand why I get this error.


You can use this code to convert the string to array.Remove the brackets and split the string with comma.

var myStr = "[1,2,3,4,5]";
var arr = myStr.replace(/^\[|\]$/g,'').split(','); // converted array