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

Helmut Michael Juskewycz
· 2 min read
Post featured image

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:

[gist id=06a8feb10f20345b31d7]

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.

Latest articles

Clock calendar notifications in harmony

Start your 14-day free trial