Javascript is the best way to avoid the dollar sign in the string used by String.prototype.replace

I want to replace the string with another. I found that if replaceValue contains "$" , the replacement will fail. So first I try to avoid the "$" on the "$$" . The code is as follows:

 var str = ..., reg = ...; function replaceString(replaceValue) { str.replace(reg, replaceValue.replace(/\$/g, '$$$$')); } 

But I think this is ugly, since I need to write 4 dollar signs.

Are there any other characteristics that I need to escape? And is there a better way to do this?

+6
source share
3 answers

There is a way to call replace that allows us not to worry about avoiding anything.

 var str = ..., reg = ...; function replaceString(replaceValue) { return str.replace(reg, function () { return replaceValue }); } 
+13
source

Your method to avoid replacing the string is correct.

According to section 15.5.4.11 of the String.prototype.replace specification of the ECMAScript 5.1 specification , all special replacement sequences begin with $ ( $& , $` , $' , $n , $nn ) and $$ specify one $ in the replacement.

Therefore, it is enough to avoid all $ with double $$ , like what you are doing right now if the replaced text is intended to be processed literally.

There is no other better way to make a replacement as far as I can see.

+6
source

Unfortunately, there is nothing you can do about it. This is how JavaScript works with regular expressions.

Here is a good article listing all the replacement patterns you should be aware of: http://es5.imtqy.com/#x15.5.4.11

+1
source

Source: https://habr.com/ru/post/981427/


All Articles