【问题标题】:Why 'ABC'.replace('B', '$`') gives AAC为什么 'ABC'.replace('B', '$`') 给 AAC
【发布时间】:2015-09-20 03:40:13
【问题描述】:

为什么这段代码会打印AAC 而不是预期的A$`C

console.log('ABC'.replace('B', '$`'));

==>

AAC

以及如何让它给出预期的结果?

【问题讨论】:

  • @anubhava:这个功能非常标准。您链接的文档中描述的 property 是非标准的。
  • @anubhava: ​RegExp.$`​ 属性是非标准的。替换字符串中的​$`​ 是标准的。
  • 后续问题:有谁知道为什么用反斜杠 \\ 转义 $ 不会产生正确的结果(即“\$`”)?
  • @greenSocksRock 因为无论出于何种原因,它都会被第二个$ 转义。

标签: javascript regex


【解决方案1】:

要插入文字$,您必须传递$$,因为$`

在匹配的子字符串之前插入字符串部分。

console.log('ABC'.replace('B', "$$`"));

请参阅documentation

其他模式:

Pattern Inserts
$$ Inserts a $.
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$<em>n</em> Where n is a positive integer less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed. If a group n is not present (e.g., if group is 3), it will be replaced as a literal (e.g., $3).
$&lt;<em>Name</em>&gt; Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., $&lt;Name&gt;). Only available in browser versions supporting named capturing groups.

JSFiddle

此外,我在上面发布的参考链接上还有更多内容。如果您仍有任何问题或疑问,您可能可以在那里找到答案,上面的屏幕截图来自答案开头发布的链接。

值得一提的是,在我看来,与上述不匹配的任何模式都不需要转义,因此$不需要'不需要逃避,$AAA 也会发生同样的情况。

在上面的 cmets 中,一位用户询问您为什么需要与另一个 $“逃脱”$:尽管我对此不太确定,但我认为也值得指出,从我们的上面说过,任何无效模式都不会被解释,因此我认为(并且在这一点上怀疑)$$ 是一个非常特殊的情况,因为它涵盖了您需要的情况将匹配项替换为美元符号后跟“模式锁定”字符,例如勾号 (`)(或者实际上是 &amp;)。

不过,在任何其他情况下,美元符号不需要转义,因此他们决定创建这样一个特定规则可能是有道理的,否则您需要在其他任何地方转义 $(我认为这可能会对任何字符串对象产生影响,因为这意味着即使在 var a = "hello, $ hey this one is a dollar"; 中,您也需要转义 $)。

如果您仍然感兴趣并想了解更多信息,请同时查看regular-expressions.info 和此JSFiddle 了解更多案例。

【讨论】:

    【解决方案2】:

    replacement 中,$ 美元符号具有特殊含义,当来自匹配的数据应用于replacement 时使用。

    MDN: String.prototype.replace(): Specifying a string as a parameter

    $$ 插入一个“$”。
    $` 插入匹配的子字符串之前的字符串部分。

    只要$ 没有产生具有特殊含义的组合,那么它就会被当作普通字符处理。但您仍应始终将其写为 $$ 替换,否则,如果添加新的 $x 组合,将来可能会失败。

    【讨论】:

    • $ 符号本身不会导致这种行为,只有美元+反勾号组合
    • @exebook 确保它自己不会有问题。但$ 仍然具有特殊含义。类似于-[a-f][af-] 之间的差异)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2015-06-27
    • 2023-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多