Is it necessary to escape the replacement string in a String.replace() call with a regular expression?

前端 未结 2 1338
梦毁少年i
梦毁少年i 2021-01-21 09:45

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##\";
         


        
相关标签:
2条回答
  • 2021-01-21 10:01

    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 Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
    0 讨论(0)
  • 2021-01-21 10:16

    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);

    0 讨论(0)
提交回复
热议问题