使用以下代码:
var x = 'foo';
console.log(x.replace(x, "\\$&"));
输出为“\foo”,如下所示:http://jsfiddle.net/mPKEx/
为什么不是
'\\$&"?
我将所有 x 替换为“\$&”,这只是一个计划中的旧字符串,那么为什么 string.replace 会在函数的第二个参数不应该做任何事情时进行一些疯狂的替换,除了被替换为...
最佳答案
$& 是Javascript 字符串替换中的一个特殊引用。它指向匹配的字符串。
$$ - Inserts a "$" $& - Refers to the entire text of the current pattern match. $` - Refers to the text to the left of the current pattern match. $' - Refers to the text to the right of the current pattern match. $n or $nn - Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
( Reference )
关于javascript - 奇怪的 Javascript 字符串用 $& 替换行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12311192/