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

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


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

Tags:

Javascript