[英]Odd JavasScript string replace behavior with $&
With the following code: 使用以下代码:
var x = 'foo';
console.log(x.replace(x, "\\$&"));
The output is '\\foo', as shown here: http://jsfiddle.net/mPKEx/ 输出为'\\ foo',如下所示: http : //jsfiddle.net/mPKEx/
Why isn't it 为什么不呢
'\\$&"?
I am replacing all of x with "\\$&" which is just a plan old string so why is string.replace doing some crazy substitution when the 2nd arg of the function isn't supposed to do anything except get substitued in... 我用“\\ $&”替换所有的x,这只是一个计划旧的字符串,所以为什么string.replace做了一些疯狂的替换,当函数的第二个arg不应该做任何事情,除了得到替换...
$& is a special reference in Javascript's string replace. $&是Javascript的字符串替换中的特殊参考。 It points to the matched string.
它指向匹配的字符串。
$$ - 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.
In your case: 在你的情况下:
var x = 'foo';
console.log(x.replace(x, function() {return '\\$&'}));
See the differences: http://jsfiddle.net/mPKEx/10/ 看到差异: http : //jsfiddle.net/mPKEx/10/
You can specify a function as the second parameter . 您可以将函数指定为第二个参数 。 The above-mentioned special replacement patterns ($$, $&, $`, $', $n or $nn) do not apply in this case.
在这种情况下,上述特殊替换模式($$,$&,$`,$',$ n或$ nn) 不适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.