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

前端 未结 3 1111
时光说笑
时光说笑 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:49

    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 });
    }
    

提交回复
热议问题