when I use regular expressions. If I use $1 , I get the same result as w...">

The difference between $ 1 and $ & in regular expressions

I came across $& when I use regular expressions. If I use $1 , I get the same result as with $& . What is special about $& , and where is it documented ?

When I search for "regex + $ &" on duckduckgo or google I cannot find matching matches.

In the example below, you can use $1 or $& . What is special about $ &, and why does it exist?

See fiddle with an example

 <div id="quotes"> <ul> <li>! <ul> <li><b>Let go!</b></li> <li>Variant translations: <b>Let ride!</b></li> <li><b>Let drive!</b></li> <li><b>Off we go!</b></li> </ul> </li> </ul> <ul> <li><i>   -,  ,    . ,      ,    !</i> <ul> <li><b>Orbiting Earth in the spaceship, I saw how beautiful our planet is. People, let us preserve and increase this beauty, not destroy it!</b></li> </ul> </li> </ul> </div> <script> var quotes = document.getElementById("quotes"), html = quotes.innerHTML, match = /(let)/gi; // $1 gives same result quotes.innerHTML = html.replace(match, "<mark>$&</mark>"); </script> 
+6
source share
3 answers

$& and $1 do not match.

You get the same value because you included the entire template in the capture group.

$& is a backlink to the entire match, and $1 is a backlink to the load captured with the capture of group 1.

See the MDN String#replace() link :

$& ; $n or $nn Where n or nn are decimal numbers, insert the string n th in semicolons if the first argument was a RegExp object.

More information about replacing backlinks can be found on the regular-expressions.info page .

+4
source

$& returns the entire matched string, and $1 , $2 , ... returns the captured match. I know this sounds weird, but see perlre for more information .

Consider the following:

 'abc abc'.replace(/(a)(b)./g, '$1'); // aa 'abc abc'.replace(/(a)(b)./g, '$2'); // bb 'abc abc'.replace(/(a)(b)./g, '$&'); // abc abc 
+2
source

$& is a "replacement" (placeholder for something to be replaced) for full compliance (all agreed text). $1 is a "replacement" for the first capture group.

So:

 var str = "test".replace(/s(t)/, "$&$1"); 

gives us

  testt

since $& is st and $1 is t .

+2
source

All Articles