gpt4 book ai didi

javascript - 为什么 'ABC' .replace ('B' , '$` ') 给出 AAC

转载 作者:IT王子 更新时间:2023-10-29 02:50:33 25 4
gpt4 key购买 nike

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

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

==>

AAC

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

最佳答案

插入文字 $你必须通过 $$ ,因为 $` :

Inserts the portion of the string that precedes the matched substring.

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).
$<<em>Name</em>> 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., $<Name>). Only available in browser versions supporting named capturing groups.

JSFiddle

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

值得一提的是,在我看来,任何与上述不匹配的模式不需要转义,因此$不需要转义,同样的故事发生在$AAA .

在上面的评论中,一位用户询问了为什么你需要“转义”$与另一个$ :尽管我对此不是很确定,但我认为还值得指出的是,从我们上面所说的,任何无效模式都不会被解释,因此我认为(并且怀疑,此时)$$是一种非常特殊的情况,因为它涵盖了您需要用美元符号后跟“模式锁定”字符替换匹配项的情况,例如刻度线 ( ` )(或者实际上是 &)作为另一个)。

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

如果您仍然感兴趣并想阅读更多内容,请查看 regular-expressions.info还有这个JSFiddle更多案例。

关于javascript - 为什么 'ABC' .replace ('B' , '$` ') 给出 AAC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31187452/

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