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.