Home / Blog / Dev Bit: How to reuse matched value of regex in JavaScript's replace() function

Dev Bit: How to reuse matched value of regex in JavaScript's replace() function

Developer resources
Helmut Juskewycz
CEO & Founder of LingoHub

Last updated

11/19/2020

Read time

4 min

Best for

Developers

You create - Lingohub localizes

We all know the replace() function for JavaScript Strings and that it is possible to do really fancy things by using regular expressions to replace a (sub)string. What I didn’t know was that there are special $ references you can use in the replace() function. Of course there is $1, $2,… to get the first, second finding, BUT did you know $& is also available?

$& reinserts the whole regex match

Here is an example how it works:

The usage of $& is basically just the shorthand of using the replace() function with a function as second parameter:

text.replace(regex, function(m){ return ''+m+'';});

When you use replace(RegExp, function) then the function is called with the following arguments:

  • The matched substring

  • Match1,2,3,4 etc (parenthesized substring matches)

  • The offset of the substring

  • The full string

When to use it?

It will make sense to use $& if you can’t change the regex per se, e.g. if you get it from a server. Or, secondly you just don’t want to employ a captured group in your regular expression ;)

More information:

LingoHub - Translation Management for Developers

This article is provided by LingoHub, a translation management software. It is used by development and product teams from all over the world to manage software translations more productively.

Related articles