简体   繁体   English

用正则表达式替换多个字符串

[英]Multiple string replace with a Regular Expression

I try to replace some multiple strings with an abbreviation .. . 我尝试用缩写来代替某些多串.. If a string occurrences more than 2 times then it is to replace with string..string . 如果字符串出现两次以上,则将其替换为string..string Eg the string is as follows: 例如,字符串如下:

var str = 'i,u,br,br,p,p,p,p,br,br,br,br,div,div,div,div,br,br,br,p';
// The result should be as follows:
str = 'i,u,br,br,p..p,br..br,div..div,br..br,p';

Here is my approach, but it doesn't work proper: 这是我的方法,但无法正常工作:

str = str.replace(/((,\w+)){3,}/igm, ',$1...$1');

Do you have any idea how can I do it right? 你知道我该怎么做吗? Thanks. 谢谢。

Sure: 当然:

(\b\w+)(?:,\1){2,}

Demo 演示

What was required is for all the words to be the same, so you have to use a backreference in the pattern. 要求所有单词都相同,因此您必须在模式中使用反向引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM