How to split a comma separated string and process in a loop using JavaScript?
7 Answers
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]);
}
Edit:
After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:
'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]
This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.
And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:
myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
console.log(myString);
});
3 Comments
'Hello, cruel , world!'.trim().split(/\s*,\s*/). Wont work in IE8''.split(/\s*,\s*/); results str.length === 1 instead of 0, how fix it?Like this:
var str = 'Hello, World, etc';
var myarray = str.split(',');
for(var i = 0; i < myarray.length; i++)
{
console.log(myarray[i]);
}
4 Comments
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.Try the following snippet:
var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this
Edit:
The following snippet will allow you to split, manipulate each element and get the results in an array:
const string = "this,is,a,string";
const array = string.split(",")
.map((item, i) => `Item ${i} => ${item}`);
console.log(array)
Example using async/await in a forEach loop:
const files = "name1,name2,name3"
if (files.length) {
await forEachAsync(files.toString().split(','), async (item) => {
console.log(item)
});
1 Comment
I'm not a JavaScript expert, but it seems simple enough for me (Firefox console):
10:24:28.561 "a,b,c".split(',').forEach(e => { console.log('iteM:' + e)})
10:24:28.586 iteM:a debugger eval code:1:43
10:24:28.586 iteM:b debugger eval code:1:43
10:24:28.597 iteM:c
comma separated string