How can I convert a comma-separated string to an array?
I have a comma-separated string that I want to convert into an array, so I can loop through it.
Is there anything built-in to do this?
For example, I have this string
var str = "January,February,March,April,May,June,July,August,September,October,November,December";
Now I want to split this by the comma, and then store it in an array.
Solution 1:
var array = string.split(',');
MDN reference, mostly helpful for the possibly unexpected behavior of the limit
parameter. (Hint: "a,b,c".split(",", 2)
comes out to ["a", "b"]
, not ["a", "b,c"]
.)
Solution 2:
Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.
var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");
Adding a loop like this,
for (a in temp ) {
temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}
will return an array containing integers, and not strings.