Replace string containing $& in JavaScript regex

var htmlstring = "<div>{NAME}</div>";
var name = "$&lt;Anonymous&gt;"  //Encoded form of "$<Anonymous>";

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

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

Specifying a string as a parameter

The replacement string can include the following special replacement patterns:

Pattern Inserts
$$ 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. Note that this is 1-indexed. If a group n is not present (e.g., if group is 3), it will be replaced as a literal (e.g., $3).
$<Name> Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., $<Name>). Only available in browser versions supporting named capturing groups.

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