Jamgreen Jamgreen - 1 year ago 130
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.

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