Ruben Ruben - 4 months ago 11x
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?


Try this (edited):

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