It is possible to use non-capturing groups for this, e.g.
$ node
> 'foobar'.replace(/(foo)(?:bar)/g, '$1test')
'footest'
In the second parameter of String.replace, the special notation of $1
references the first capturing group, which is (foo)
in this case. By using $1test
, one can think of $1
as a placeholder for the first matching group. When expanded, this becomes 'footest'
.
For more in depth details on the regular expression, view what it matches here.