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

前端 未结 2 1339
梦毁少年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: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);

提交回复
热议问题