最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Odd JavasScript string replace behavior with $& - Stack Overflow

programmeradmin2浏览0评论

With the following code:

var x = 'foo';
console.log(x.replace(x, "\\$&"));​

The output is '\foo', as shown here: /

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...

With the following code:

var x = 'foo';
console.log(x.replace(x, "\\$&"));​

The output is '\foo', as shown here: http://jsfiddle/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...

Share Improve this question edited Sep 7, 2012 at 3:19 user166390 asked Sep 7, 2012 at 3:07 asutherlandasutherland 2,9694 gold badges38 silver badges51 bronze badges 3
  • 1 It's weird that you just happened to choose those characters. From your perspective it might seem like a bug. – ChaosPandion Commented Sep 7, 2012 at 3:14
  • I was replacing something with a very large block of text that happened to have those characters in it, it took me forever to narrow it down to those characters being the cause. – asutherland Commented Sep 7, 2012 at 3:19
  • 25% of my job is tracking down little mysteries like that. – ChaosPandion Commented Sep 7, 2012 at 3:21
Add a ment  | 

2 Answers 2

Reset to default 9

$& is a special reference in Javascript's string replace. 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.

(Reference)

In your case:

var x = 'foo';
console.log(x.replace(x, function() {return '\\$&'}));

See the differences: http://jsfiddle/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.

发布评论

评论列表(0)

  1. 暂无评论