Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string containing $& in JavaScript regex

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?

like image 720
Siva S Avatar asked Dec 02 '15 10:12

Siva S


People also ask

How do you replace a specific part of a string in Java?

One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.

What is the difference between Replace () and replaceAll ()?

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)


1 Answers

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.

like image 155
Wiktor Stribiżew Avatar answered Sep 27 '22 21:09

Wiktor Stribiżew