使用$&奇数JavasScript字符串替换行为

asu*_*and 6 javascript regex string replace

使用以下代码:

var x = 'foo';
console.log(x.replace(x, "\\$&"));?
Run Code Online (Sandbox Code Playgroud)

输出为'\ foo',如下所示:http://jsfiddle.net/mPKEx/

为什么不呢

'\\$&"?
Run Code Online (Sandbox Code Playgroud)

我用"\ $&"替换所有的x,这只是一个计划旧的字符串,所以为什么string.replace做了一些疯狂的替换,当函数的第二个arg不应该做任何事情,除了得到替换...

Ani*_*han 9

$&是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.

(参考)