Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - Difference between $1 and $& in regular expressions

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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  Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

More details on replacement backreferences can be found at regular-expressions.info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...