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/
"(^|\\s)(a|b)"?"(^|\\s)([ab])"(a|bc).