Jamgreen
Jamgreen

Reputation: 11039

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.

Upvotes: 1

Views: 3205

Answers (5)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may add an alternative branch and enclose it with a capturing group and then use a replace callback method where you can analyze the match groups and perform the replacement accordingly:

var s = ',some text,,,,more text,';
var res = s.replace(/^,|,$|(,+)/g, function(m,g1) {
  return g1 ? ',' : '';
});
console.log(res);

To split with commas and get no empty entries in the resulting array, use a simple

console.log(',some text,,,,more text,'.split(',').filter(Boolean));

Upvotes: 3

Tushar
Tushar

Reputation: 87203

Remove the leading and trailing commas, and then replace multiple consecutive commas by single comma

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

,+ will match one or more comma, g-global flag to replace all occurrences of it.

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

str = str.replace(/^,|,$|(,)+/g, '$1');
console.log(str);

Upvotes: 3

Cerbrus
Cerbrus

Reputation: 72857

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.

Upvotes: 3

antoni
antoni

Reputation: 5546

What about one replace only like: ",some text,,,,more text,".replace(/(^,)|(,$)|,(?=,)/g, '');

[EDIT]

Note that lookbehinds don't work in javascript. so you can only use a lookahead like so.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You could add a positive lookahead with another comma.

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

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

console.log(str);

Upvotes: 2

Related Questions