How to split a comma separated string and process in a loop using JavaScript?
views:
70answers:
3
+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
2010-07-14 10:05:32
Wouldn't the argument to "split" be ',' ?
Night Shade
2010-07-14 10:06:22
@Archangel: It is, fixed even before your comment.
Sarfraz
2010-07-14 10:07:04
what is this "console.log" what is the use of that?
learner
2010-07-14 10:07:44
@learner: You can replace it with `alert(myarray[i]);`
Sarfraz
2010-07-14 10:08:43
ok thank you :-)
learner
2010-07-14 10:10:42
@learner: You are welcome...
Sarfraz
2010-07-14 10:12:47
@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
2010-07-14 15:26:23
+2
A:
Try the following snippet:
var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this
Anax
2010-07-14 10:06:27
+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
2010-07-14 10:49:26