【问题标题】:Is String.prototype.replace() buggy? [duplicate]String.prototype.replace() 有问题吗? [复制]
【发布时间】:2021-03-05 11:49:08
【问题描述】:

考虑以下sn-p,

console.log('A B'.replace('A', "$'"))

我希望输出是:$' B

但实际输出: B B

有人可以解释这种行为吗?

【问题讨论】:

标签: javascript string replace prototype


【解决方案1】:

$ 表示替换字符串中的placeholder

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 nth 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;Name&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.

【讨论】:

  • 你为什么不把它当作骗子关掉?
【解决方案2】:

根据 MDN 文档和 cmets 中的引用:

$' 插入匹配子串之后的字符串部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多