javascript - Better Way to Escape Dollar Signs in the String Used By String.prototype.replace

前端 未结 3 1114
时光说笑
时光说笑 2020-12-19 00:02

I want to replace a string by another. I found when the replaceValue contains \"$\", the replace will fail. So I am trying to escape \"$\" by

3条回答
  •  再見小時候
    2020-12-19 00:48

    Your method to escape the replacement string is correct.

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

    Therefore, it is sufficient to escape all $ with double $$ like what you are doing right now if the replacement text is meant to be treated literally.

    There is no other concise way to do the replacement as far as I can see.

提交回复
热议问题