Convert string with commas to array Convert string with commas to array arrays arrays

Convert string with commas to array


For simple array members like that, you can use JSON.parse.

var array = JSON.parse("[" + string + "]");

This gives you an Array of numbers.

[0, 1]

If you use .split(), you'll end up with an Array of strings.

["0", "1"]

Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.


If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.

var array = string.split(",").map(Number);


Split it on the , character;

var string = "0,1";var array = string.split(",");alert(array[0]);


This is easily achieved in ES6;

You can convert strings to Arrays with Array.from('string');

Array.from("01")

will console.log

['0', '1']

Which is exactly what you're looking for.