70

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

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
DEVOPS
  • 18,190
  • 34
  • 95
  • 118
  • 2
    Possible duplicate of [How do I split a string, breaking at a particular character?](http://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Fuzzybear Apr 20 '17 at 12:38
  • Does not look like a duplicate. Here is `comma separated string` – vitaliis Feb 23 '22 at 17:12

6 Answers6

128

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);
});
Nirmalya Ghosh
  • 2,298
  • 3
  • 18
  • 33
kzh
  • 19,810
  • 13
  • 73
  • 97
33

Like this:

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

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Wouldn't the argument to "split" be ',' ? – MD Sayem Ahmed Jul 14 '10 at 10:06
  • @Archangel: It is, fixed even before your comment. – Sarfraz Jul 14 '10 at 10:07
  • what is this "console.log" what is the use of that? – DEVOPS Jul 14 '10 at 10:07
  • 2
    @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 Jul 14 '10 at 15:26
13

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)
Anax
  • 9,122
  • 5
  • 34
  • 68
2

Please run below code may it helps you :)

var str = "this,is,an,example";
var strArr = str.split(',');
var data = "";
for(var i=0; i<strArr.length; i++){
  data += "Index : "+i+" value : "+strArr[i]+"<br/>";
}
document.getElementById('print').innerHTML = data;
<div id="print">
</div>
Renish Gotecha
  • 2,232
  • 22
  • 21
1

you can Try the following snippet:

var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)

and your output like that

My Result: H,w are y,u d,ing t,day?
Aakash Sajjad
  • 97
  • 1
  • 5
0

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)
    });
Adriano Campos
  • 1,121
  • 7
  • 14