tags:

views:

70

answers:

3

How to split a comma separated string and process in a loop using JavaScript?

+5  A: 

Like this:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}
Sarfraz
Wouldn't the argument to "split" be ',' ?
Night Shade
@Archangel: It is, fixed even before your comment.
Sarfraz
what is this "console.log" what is the use of that?
learner
@learner: You can replace it with `alert(myarray[i]);`
Sarfraz
ok thank you :-)
learner
@learner: You are welcome...
Sarfraz
@learner: `console.log` is a logging function exposed by at least Firebug and WebKit-based browsers. It's generally less intrusive than popping up alert dialogs. One downside is that you have to remember to either remove the calls in production or define an empty `console.log` function, since it won't be available everywhere.
Matthew Crumley
+2  A: 

Try the following snippet:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this
Anax
I think you mean `alert(splits[0]);`
Andy E
@Andy E: indeed, it was already fixed before I would read your comment, but well spotted nevertheless.
Anax
+1  A: 

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++)
{
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}
kzh