最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove consecutive commas with regex - Stack Overflow

programmeradmin1浏览0评论

I use

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

to remove leading and trailing mas.

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

So ,some text,,more text, should bee some text,more text?

One way would be to chain with

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

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

I use

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

to remove leading and trailing mas.

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

So ,some text,,more text, should bee some text,more text?

One way would be to chain with

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

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

Share Improve this question asked Oct 19, 2016 at 7:27 JamgreenJamgreen 11.1k32 gold badges122 silver badges231 bronze badges 1
  • Since you appear to be .split(',')-ing the resulting string, I've written an answer that easily works around the extra mas, immediately returning the split string you're looking for. – Cerbrus Commented Oct 19, 2016 at 8:39
Add a ment  | 

5 Answers 5

Reset to default 3

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 ma's.

Remove the leading and trailing mas, and then replace multiple consecutive mas by single ma

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

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

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

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

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 mas and get no empty entries in the resulting array, use a simple

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

You could add a positive lookahead with another ma.

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

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

console.log(str);

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.

发布评论

评论列表(0)

  1. 暂无评论