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 e.g. I have this string
var str = "January,February,March,April,May,June,July,August,September,October,November,December";
now want to split this by comma and store in Array object
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"]
.)I had a similar issue, but more complex as I needed to transform a csv into an array of arrays (each line is one array element that inside has an array of items split by comma).
The easiest solution (and more secure I bet) was to use PapaParse (http://papaparse.com/) which has a "no-header" option that transform the csv into an array of arrays, plus, it automatically detected the "," as my delimiter.
Plus, it is registered in bower, so I only had to:
and then use it in my code as follows:
I really liked it.
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.
adding a loop like this
will return an array containing integers, and not strings.
Hmm split is dangerous imho as a string can always contain a comma, observe the following:
So how would you interperate that? and what do you WANT the result to be? an array with:
even if you escape the comma you'd have a problem.
Quickly fiddled this together:
Feel free to use / edit it :)
Note that the following:
will alert 1
Return function
its accept string and objectstrings
JSFiddle https://jsfiddle.net/7ne9L4Lj/1/