darkhorse
darkhorse

Reputation: 8722

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:

JSON.parse(myStr)

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]"

EDIT:

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.

Upvotes: 0

Views: 76

Answers (4)

Ankh
Ankh

Reputation: 91

For an array with number this works:

var myStr = "[1,2,3,4,5]";
var array = JSON.parse(myStr);

console.log(array);

output:

[1, 2, 3, 4, 5]

Upvotes: 0

ninjawarrior
ninjawarrior

Reputation: 326

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 

Upvotes: 1

Sam Hajari
Sam Hajari

Reputation: 354

Try var array = JSON.parse("[" + myStr + "]"); This will give you an array [1,2,3,4,5]

Upvotes: 1

Nour
Nour

Reputation: 1497

You should write it like so

var myStr2 = '["cats","dogs","elephants"]' ; 
obj = JSON.parse(myStr2);

Upvotes: 2

Related Questions