【问题标题】: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). |
$<Name> |
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. |
【解决方案2】:
根据 MDN 文档和 cmets 中的引用:
$' 插入匹配子串之后的字符串部分。