简体   繁体   中英

`string.replace` weird behavior when using dollar sign ($) as replacement

I found a bug in my JavaScript code that I have isolated to a string replace that is acting in a way I didn't expect. Here is an example of the code:

var text = "as";
text = text.replace(text,"$\'");
console.log(text);

This prints an empty string to the console. I was expecting it to print $' to the console. Can anyone explain this?

为了使用$在生成的字符串,用$$$在JavaScript的正则表达式的特殊含义和字符串replace方法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/字符串/替换#Specifying_a_string_as_a_parameter

If I don't know what is in my replacement string I use

replaceWith = "might have 2 $ signs $$ $$$ $$$$"
"a b c".replace("b", replaceWith) // unexpected result
"a b c".replace("b", function(){return replaceWith}) // no surprises

Actually, the most straight forward answer to this question is to use a function for the replacement string, because the w3c spec states that this result will not be affected by special characters.

 var str = "abc {def} ghi"; console.log(str.replace("{def}", function() { return "foo$'bar"; })); // result is // "abc foo$'bar ghi"

The MDN documentation for that is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM