Short question. How can I convert a string to the JS array?

Look at the code:

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

In this case, alert would popup a 0,1. When it would be an array, it would popup a 0, and when alert(array[1]); is called, it should popup the 1.

Is there any chance to convert such string into a JS array?

share|improve this question
Depending why you want this, strings and arrays are already very similiar (i.e. string[0] === '0' in your question), in most cases you can treat a string as an array of chars and use array methods on it. – Paul S. Nov 7 '12 at 15:19
@PaulS.: That will fail in IE8 and lower. – I Hate Lazy Nov 7 '12 at 16:00

3 Answers

up vote 4 down vote accepted

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);
share|improve this answer
Also be aware that JSON.parse(); is not available in IE6, IE7. I think in this case the String.split(','); is easier. – scunliffe Nov 7 '12 at 15:15
@scunliffe: True, a shim would be needed, or one could take the jQuery approach to shim it var array = (new Function("return [" + string + "];"))(). Using .split() is alright if Numbers aren't needed, otherwise you'd need to map the result. – I Hate Lazy Nov 7 '12 at 15:18
@Downvoter: Try to describe what is wrong with the answer so that I can demonstrate how you're wrong. – I Hate Lazy Nov 7 '12 at 15:59

Split it on the , character;

var string = "0,1";
var array = string.split(",");
alert(array[0]);
share|improve this answer

you can use split. http://www.w3schools.com/jsref/jsref_split.asp

"0,1".split(',')

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.