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> $& 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 :
$&;$nor$nnWherenornnare decimal numbers, insert the stringnth in semicolons if the first argument was aRegExpobject.
More information about replacing backlinks can be found on the regular-expressions.info page .
$& 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