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

谁都会走 提交于 2019-11-29 10:00:30
Leonid

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

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

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.

Unfortunately, nothing you can do about it.
It's just how JavaScript works with regular expressions.

Here's a good article with the list of all replacement patterns you should be aware of: http://es5.github.io/#x15.5.4.11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!