ozen
ozen

Reputation: 47

Consecutive duplicate words to change with regex

var str="Foo bar bar end."
var word="bar"
var regex = new RegExp("([\\s]|^|>)("+word+")(<|[\\s]|$)", "gi");
str=str.replace(regex,' <span class="selected">$2</span> ');

result:

Foo <span class="selected">bar</span> bar end.

Why only first bar changed?

Upvotes: 2

Views: 82

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Because of overlapping matches. ie, your last capturing group consumes the trailing delimiter. Inorder to make it not to consume the following character, change the last capturing group to a positive lookahead pattern which won't consume any character but do assertion.

var regex = new RegExp("([\\s>]|^)("+word+")(?=[<\\s]|$)", "gi");
str=str.replace(regex,'$1<span class="selected">$2</span>');

Upvotes: 2

Related Questions