Jamgreen Jamgreen - 1 month ago 9
Javascript Question

Remove consecutive commas with regex

I use

str.replace(/(^,)|(,$)/g, '')


to remove leading and trailing commas.

How can I extend it so I also remove two consecutive commas?

So
,some text,,more text,
should become
some text,more text
?

One way would be to chain with

str.replace(/(^,)|(,$)/g, '').replace(/,,/g, ',')


but then
,some text,,,,more text,
will become
some text,,more text
instead of
some text,more text
.

Answer

Since you appear to be using the str as a source for an array, you can replace all the .replace calls with:

var str = ",some text,,,,more text,";

var resultArray = str.split(',') // Just split the string.
  .filter(function(item){        // Then filter out empty items
    return item !== '';
  });

console.log(resultArray)

No need to worry about leading, trailing or double comma's.

Comments