1

I am trying to capture a matched group in a regular expression, and inside of that regular expression, inside of that matched group I need to replace a character AND duplicate the match. So for example

foo-bar-baz

I would need to do /foo-(\w+)-baz/ but I would want to replace all 'r' in that matched group with a 't' and duplicate it so like

foo-barbat-baz

There could be multiple matches in the same string, so like test-string-foo-bar-baz-another-foo-bar-baz would become test-string-foo-barbat-baz-another-foo-barbat-baz

I know I can use $1 .. etc in .replace but that doesn't handle an arbitrary amount of matches. I also know about \n (e.g. \1) and \k but none of these seem to help.

I've tried looping through the matches, but I can't figure out how to tell about the match position in the string, so I can 'insert' the replacement after it, and then once I replace it, the string length changes so the next match position wouldn't be correct.

1 Answer 1

1

You may use this lambda approach in .replace:

const s = 'test-string-foo-bar-baz-another-foo-bar-baz';

var repl = s.replace(/(foo-)(\w+)(-baz)/g,
    (m, g1, g2, g3) => g1 + g2 + g2.replace(/r/g, "t") + g3);

console.log(repl);

RegEx/lamnda Details:

  • (foo-)(\w+)(-baz): Use 3 capture groups to capture foo- in 1st, \w+ in 2nd and -baz in 3rd group
  • (m, g1, g2, g3): Makes available m (full match) and gN (Nth capture group) to lambda expression
  • g1 + g2 + g2.replace(/r/g, "t") + g3: Concatenates g1 + g2 + g3 while duplicating g2 by replacing r with t
Sign up to request clarification or add additional context in comments.

6 Comments

Nice, works also without s param in replace
I am working on it, as you can imagine this isn't quite my case but I am modifying my complex re to see if I can accomplish this with an arbitrary number of matches
as you can imagine this isn't quite my case: Sorry I don't get you. This does match your expected output and does exactly what you've asked in question. please clarify what is not working for you?
sorry this is exactly what I was asking for. What I meant is I need to adapt it to my code, and figure out my regular expression, as i'm not really searching for 'foo-bar-baz' but complex strings. I got it working last night, thanks for the help.
Good to know that you got it working but please understand an answer can only address a stated problem not something that hasn't been mentioned anywhere.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.