Ruben Ruben - 1 year ago 86
Javascript Question

What is wrong with this regex for comma-separated string?

I'm trying to convert a comma or semicolon separated string into an array, but handling before conversion several omission from users (double commas, space after comma or semicolon). In the example:

myStr = "item1, item2,,, this is item3; item4 , "

I want to get:

myArray = ["item1", "item2", "this is item3", "item4"]

My actual regex is:

myArray = myStr.split(/[(,\s);,]+/);

But, although I'm adding parenthesis to the combination comma-space
the regex are catching the spaces inside the third item. Any advice what could be wrong with regex?

Answer Source

Try this (edited):

var myStr = "item1, item2,,, this is item3; item4 , ";
var myArray = myStr.split(/\s*[,;]+\s*/).filter(Boolean);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download