Replace string containing $& in JavaScript regex

前端 未结 2 1559
一生所求
一生所求 2021-01-19 16:11

I need to replace a html string with a dynamic value.This dynamic value(HTML encode) is to replace a pattern in the html string.

var htmlstring = \"

        
相关标签:
2条回答
  • 2021-01-19 17:13

    In JavaScript, to replace with $, you need to escape the dollar symbol with another dollar symbol, otherwise, $& is treated as a backreference to the whole matched value (i.e. {NAME} here).

    You need to use

    var name = "$$<Anonymous>"
                ^^
    

    var htmlstring = "<div>{NAME}</div>";
    var name = "$$&lt;Anonymous&gt;"  //Encoded form of "$<Annonymous>";
    html = htmlstring.replace(/{NAME}/g,name);
    document.write(html);

    See String#replace reference:

    Pattern Inserts
    $$        Inserts a "$".
    $&        Inserts the matched substring.

    0 讨论(0)
  • 2021-01-19 17:14

    From Docs of replace, $& Inserts the matched substring.

    You can use the replace callback to get the $& literal in the replaced string.

    var htmlstring = "<div>{NAME}</div>";
    var name = "$&lt;Anonymous&gt;" //Encoded form of "$<Annonymous>";
    var html = htmlstring.replace(/{NAME}/g, function(m) {
      return name;
    });
    
    console.log(html);
    document.write(html);

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