6

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 = "<div>{NAME}</div>";
var name = "$&lt;Anonymous&gt;"  //Encoded form of "$<Anonymous>";
html = htmlstring.replace(/{NAME}/g,name);

I need to get "$<Anonymous>" as output but i get "{NAME}lt;Anonymous>" as output.This is because "$&" matches the whole match "{NAME}" and replace "$&" with "{NAME}".

Can anyone suggest how can I achieve this in JavaScript?

Siva Prakash
  • 43
  • 1
  • 6
Siva S
  • 69
  • 1
  • 4

2 Answers2

8

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

enter image description here

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);
Tushar
  • 85,780
  • 21
  • 159
  • 179
6

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 = "$$&lt;Anonymous&gt;"
            ^^

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563