`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?


Solution 1:

In order to use $ in resulting string, use $$ as $ has special meaning in JavaScript Regular Expressions and String replace method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter

Solution 2:

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

Solution 3:

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