2

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. E.g. 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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

And yet still some folks claim that regular expressions are not, in fact, a dark art...
@David regexes are great once you grasp them, they can make many things so much simpler ;)
Slight issue with this - it doesn't check that the initial word is a "full" word - i.e. preceded by , or at the beginning of the string. e.g. "i,u,br,br,p,p,p,p,br,br,br,br,dddiv,div,div,div,div,br,br,br,p" will produce unexpected behavior.
Quick question, is ?: really needed or it's only for the .match function to not capture this group?
@Karl-Andé it's not required at all here, it's just a simple optimization
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.