0

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/

4
  • 1
    Any reason you can't stick to using two capture groups, ala: "(^|\\s)(a|b)"? Commented Dec 29, 2015 at 16:29
  • @JamesThorpe KISS, "(^|\\s)([ab])" Commented Dec 29, 2015 at 16:33
  • @AvinashRaj Yeah, assuming it's only ever single characters like this that works too, and wouldn't for instance ever need to be (a|bc). Commented Dec 29, 2015 at 16:34
  • @gipadm: How simplified is your example? If the answer posted does not help you, you can make use of a callback function inside the replace method. Commented Dec 29, 2015 at 17:00

1 Answer 1

3

You can change your regex to:

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

Working demo

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

Comments

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.