Skip to content

JavaScript split string by comma

  • by

Use the split() method to split a comma-separated string and process it in a loop using JavaScript. The split() the method splits a string into an array of substrings and returns the new array.

string.split(comma) // 
string.split(',')

JavaScript splits string by comma

Simple example code.

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

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

Output:

JavaScript split string by comma

Add trim to remove the initial whitespaces left.

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]);
}

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!"]

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS split topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading