Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

Is there anything built-in to do this?

Of course I can write a custom function to do this. Or even better import one of the many existing libraries already written and well tested to process comma separated values, such as jquery-csv. But is there something built in?

like image 910
Blankman Avatar asked May 18 '10 14:05

Blankman


People also ask

How can I convert a comma separated string to an array in PHP?

Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter.


1 Answers

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"].)

like image 54
Matchu Avatar answered Sep 23 '22 21:09

Matchu