I have stumbled upon $&
when I use regular expressions. If I use $1
I get the same result as with $&
. What is special with $&
, and where is it documented?
When I search for "regular expression +$&" on duckduckgo or google I can't find any relevant matches.
In the example below it is possible to use $1
or $&
. What is special about $&, and why does it exist?
See a fiddle with the example
<div id="quotes">
<ul>
<li>Поехали!
<ul>
<li><b>Let's go!</b></li>
<li>Variant translations: <b>Let's ride!</b></li>
<li><b>Let's 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>
$1 is the first positional parameter passed to the shell. The general format can be written as ${var#patt} too, where patt is matched (shortest match from start) in $var and deleted. Example: var="first=middle=last" echo "${var#*=}" Output: middle=last.
Shell scripts have access to some "magic" variables from the environment: $0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.
You use a dollar sign (' $ ') to refer to a field in an awk program, followed by the number of the field you want. Thus, $1 refers to the first field, $2 to the second, and so on. (Unlike in the Unix shells, the field numbers are not limited to single digits. $127 is the 127th field in the record.)
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.
$&
is a "replacement" (placeholder for something to be substituted in) for the full match (all the matched text). $1
is a "replacement" for the first capture group.
So:
var str = "test".replace(/s(t)/, "$&$1");
gives us
testt
because the $&
is st
and the $1
is t
.
The $&
and $1
are not the same.
You get the same value because you enclosed the whole pattern in a capturing group.
The $&
is a backreference to the whole match, while $1
is a backreference to the submatch captured with capturing group 1.
See MDN String#replace()
reference:
$&
Inserts the matched substring.$n
or$nn
Wheren
ornn
are decimal digits, inserts then
th parenthesized submatch string, provided the first argument was aRegExp
object.
More details on replacement backreferences can be found at regular-expressions.info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With