user911
user911

Reputation: 1559

Replace all with special character doesn't work in Javascript

I have a string

var str = "{CPARTY_<BPARTY+_DPARTY}";

I need to find all occurences of below string (find) in main string(str).

 var find = "{CPARTY_<BPARTY+_DPARTY}";

and replace it with below string.

var replace = "<span><div  ng-click='myClick($event)' title='null' data-token='CPARTY_<BPARTY+_DPARTY'  style='display: inline;'>{CPARTY_&lt;BPARTY+_DPARTY}</div></span>";

This doesn't work. That means no replacement done. No exception thrown.

str = str.replace(new RegExp(find, 'g'), replace);

This works.

str = str.replace(find, replace);

I want to use the replace all syntax.I have realized that it has something to do with special characters < and $lt; If I don't have < and $lt; , there is no issue. I know it's something very silly but can't figure it out.

jsFiddle https://jsfiddle.net/848c1as4/9/

Upvotes: 0

Views: 902

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

You have to escape the regular expression see how here. Or use a split join combo as mentioned here like this:

str = str.split(find).join(replace);

Upvotes: 1

000
000

Reputation: 27247

Several characters have special meanings in regex. For example, + and (. You'll have to treat them before using it in RegExp, by escaping them.

var str = "{CPARTY_&lt;BPARTY+_DPARTY}";
var find = "{CPARTY_&lt;BPARTY+_DPARTY}";
var safeFind = find.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&");
var replace = "<span><div  ng-click='myClick($event)' title='null' data-token='CPARTY_<BPARTY+_DPARTY'  style='display: inline;'>{CPARTY_&lt;BPARTY+_DPARTY}</div></span>";
str = str.replace(new RegExp(safeFind, 'g'), replace);

(source)

Upvotes: 5

Related Questions