gpt4 book ai didi

javascript - 正则表达式中 $1 和 $& 的区别

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:19 32 4
gpt4 key购买 nike

当我使用正则表达式时,我偶然发现了 $&。如果我使用 $1,我会得到与 $& 相同的结果。 $& 有什么特别之处,它在哪里记录

当我在 duckduckgo 或 google 上搜索“正则表达式 +$&”时,我找不到任何相关的匹配项。

在下面的示例中,可以使用 $1$&。 $& 有什么特别之处,它为什么存在?

查看 fiddle用例子

<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 不一样。

您得到相同的值,因为您将整个模式包含在一个捕获组中。

$& 是对整个匹配的反向引用,而 $1 是对捕获组 1 捕获的子匹配的反向引用。

参见 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.

有关 replacement backreferences can be found at regular-expressions.info 的更多详细信息.

关于javascript - 正则表达式中 $1 和 $& 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510746/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com