gipadm
gipadm

Reputation: 543

js regex replace multiple backreferences

I am trying to replace a string based on all matched groups by regex. I cannot use the $1..$9 backreferences as the number of groups in the regex varies.

Here is a working example with 1 group:

string = 'ab ac';
regex = new RegExp( "(^|\\s)(a)", "ig" );
template = "$1<u>$2</u>";
replace = string.replace(regex, template);

But this logic doesn't work when there is more than 1 group:

string = 'ab bc';
regex = new RegExp( "(^|\\s)(a)|(^|\\s)(b)", "ig" );
template = "$1<u>$2</u>";
replace2 = string.replace(regex, template);

What should I use as 'template' to match all groups?

This jsfiddle may make it easier to understand: https://jsfiddle.net/wfo3n7rs/

Upvotes: 0

Views: 241

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 31035

You can change your regex to:

regex = new RegExp( "(^|\\s)([ab])", "ig" );

Working demo

Upvotes: 3

Related Questions