CEO and founder of Lingohub. Envisioning a multilingual digital world. Email me if you have questions about how Lingohub can help you take your products global.

Helmut Development 0 Comments

SHARE

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:

var text = "this is a {highlighted} text"; 

var regex = /\{\S+?\}/g;
var html = text.replace(regex, '<mark>$&</mark>'); // $& = matched value = {highlight}
alert(html); // => "this is a <mark>{highlighted}</mark> text"

var regex2 = /\{(\S+?)\}/g; // you need ()-brackets to get $1
var html2 = text.replace(regex2, '<mark>$1</mark>'); // $1 = first () = highlight
alert(html2); // => "this is a <mark>highlighted</mark> text"

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 '<mark>'+m+'</mark>';});

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: