我想在JavaScript中创建String.replaceAll()方法,我认为使用正则表达式是最简洁的方法。然而,我无法确定如何将变量传递给正则表达式。我已经可以这样做了,这将用“A”替换“B”的所有实例。

"ABABAB".replace(/B/g, "A");

但我想这样做:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};

但显然,这只会替换文本“replaceThis”。。。那么如何将此变量传递到正则表达式字符串中?


当前回答

如果要获取所有出现的单词(g),请区分大小写(i),并使用边界,使其不是另一个单词中的单词(\\b):

re = new RegExp(`\\b${replaceThis}\\b`, 'gi');

let inputString=“我是John或johnny,但我更喜欢John。”;let replaceThis=“John”;let re=新RegExp(`\\b${replaceThis}\\b`,'gi');console.log(inputString.replace(re,“Jack”));

其他回答

这里是另一个replaceAll实现:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

对于任何希望在匹配方法中使用变量的人来说,这对我很有用:

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

如果使用正确的语法传递变量,可以使用下面的代码这样做。

这还有一个额外的好处,就是在同一个变量中使用标志。

此外,当涉及到\w等时,您不必在正则表达式中进行双转义。

var str=“regexVariable示例:这是我用regexVariable替换RegExp的示例。”var reVar=/(.*?)(正则表达式\w+?able)(.+?)/gi;var resStr=str.replace(新RegExp(reVar),'$1:):):)$2:)::)$3');console.log(resStr);//退货://:):)::)regexVariable:):。

原型版本符合OP的示例:

var str=“regexVariable原型:这是我用regexVariable替换RegExp的示例。”String.prototype.regexVariable=函数(reFind,reReplace){return str.replace(新RegExp(reFind),reReplace);}var reVar=/(.*?)(正则表达式\w+?able)(.+?)/gi;console.log(str.regexVariable(reVar,‘$1:):):)$2:)::)$3'));//退货://:):)::)regexVariable:):。

对于不带正则表达式的多重替换,我使用了以下方法:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

解决方案的重要部分在这里找到

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

使用此工具测试