Should I avoid string replacement in String.replace () call with regex?

I wonder if it is necessary to avoid certain characters in the replacement string of the replace operation in Javascript. I have it:

let t = "##links##";
let t2 = t.replace(/##links##/, `{"labels": ["'$'"]}`);
console.log(t2);

      

Console output:

{"labels": ["'"]}

      

which is pretty amazing. However, I can't find anything in the documentation that suggests avoiding string replacement. So what's going on here?

+3


source to share


2 answers


You need to double the character $

to replace with a literal $

:

let t = "##links##";
let t2 = t.replace(/##links##/, `{"labels": ["'$$'"]}`);
console.log(t2);
      

Run codeHide result


See Specifying a string as a parameter , listing all possible "special" combinations within the replacement part of a regular expression.



If you check this table, you will see what $

triggers the "special" sequences. So it needs to be avoided in some way. In JS, dollar is used to escape from the literal dollar symbol. $&

is a backreference to the whole match, $`

inserts the part of the string that precedes the substring, $'

inserts the part of the string that follows the matched substring. $n

is the backrefernece for group n.

So, if you have a dynamic, custom replacement string that shouldn't have backlinks, you can use

let t = "##links##";
let  rep = `{"labels": ["'$'"]}`;
let t2 = t.replace(/##links##/, rep.replace(/\$/g, '$$$$'));
console.log(t2);
      

Run codeHide result


+1


source


The 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 a matching substring.
  • $`

    Inserts the portion of a string that precedes the matched substring.
  • $'

    Inserts the portion of a string that follows a substring.
  • $n

    Where n

    is a positive integer less than 100, inserts the string n

    th in parentheses with a comma, assuming the first argument was RegExp

    .
+1


source







All Articles