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 = "$<Anonymous>" //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?
One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
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 = "$$<Anonymous>" //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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With