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

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 ;)