How can I convert a string to a JavaScript array?
Look at the code:
var string = \"0,1\";
var array = [string];
alert(array[0]);
In
More "Try it Yourself" examples below.
Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
var res = str.split(",");
Split it on the ,
character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
If the string is already in list format, you can use the JSON.parse:
var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
Why don't you do replace ,
comma and split('')
the string like this which will result into ['0', '1']
, furthermore, you could wrap the result into parseInt()
to transform element into integer type.
it('convert string to array', function () {
expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
I remove the characters '[',']' and do an split with ','
let array = stringObject.replace('[','').replace(']','').split(",").map(String);
You can use split
Reference: http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')