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##\";
Dollar sign ($
) is special in replace. If you want a single, literal dollar sign, use $$
. Otherwise, the replacement string can include the following special replacement patterns:
$$
Inserts a$
.$&
Inserts 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
Wheren
is a positive integer less than 100, inserts then
th parenthesized submatch string, provided the first argument was a RegExp object.
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);