2013-03-11 19 views
3

我试图取代像一些文字:

I need the %r for the bike.

%r被另一个值代替。

可以说我用$$$$替换%r

var text = 'I need the %r for the bike.'; 

return text.replace("%r", "$$$$"); 

非但没有预期的结果:

I need the $$$$ for the bike.

我得到:

I need the $$ for the bike.

有我丢失的东西吗?

回答

4

$是一个替换中的特殊字符,因为您需要$$以获得一个结果$登录结果。你将需要额外的$字符来获得你想要的。有关详细信息,请参阅MDN reference获取.replace()。在替换字符串

各种特殊序列为:

$$ - Inserts a "$" 
$& - Insert 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 
$n - Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. 
+0

谢谢。我认为美元符号只是用'REGEXP'替换时才做的。 – Shawn31313 2013-03-12 00:07:54