Jamgreen Jamgreen - 11 months ago 74
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?

,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 Source

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 !== '';


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