Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 238
DEVOPS Avatar asked Jul 14 '10 10:07

DEVOPS


People also ask

How do you split a comma in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you convert a string separated by a comma to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 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); }); 
like image 99
kzh Avatar answered Sep 25 '22 06:09

kzh


Like this:

var str = 'Hello, World, etc'; var myarray = str.split(',');  for(var i = 0; i < myarray.length; i++) {    console.log(myarray[i]); } 
like image 37
Sarfraz Avatar answered Sep 24 '22 06:09

Sarfraz