In wonder if it is necessary to escape certain chars in the replacement string of a replace operation in Javascript. What I have is this:
let t = \"##links##\";
You need to double the $
symbol to replace with a literal $
:
let t = "##links##";
let t2 = t.replace(/##links##/, `{"labels": ["'$$'"]}`);
console.log(t2);
See Specifying a string as a parameter listing all the possible "special" combinations inside a regex replacement part.
If you check that table, you will see that $
starts the "special" sequences. Thus, it should be escaped in some way. In JS, a dollar is used to escape the literal dollar symbol. $&
is a backreference to the whole match, $`
inserts the portion of the string that precedes the matched substring, $'
inserts the portion of the string that follows the matched substring. $n
is a backrefernece to Group n.
So, if you have a dynamic, user-defined replacement string that is not supposed to have backreferences, you may use
let t = "##links##";
let rep = `{"labels": ["'$'"]}`;
let t2 = t.replace(/##links##/, rep.replace(/\$/g, '$$$$'));
console.log(t2);