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

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

但我想这样做:

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

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


当前回答

还有Steven Penny答案的CoffeeScript版本,因为这是谷歌排名第二的结果。。。。即使CoffeeScript只是删除了大量字符的JavaScript…;)

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

在我的特殊情况下:

robot.name = hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"

其他回答

如果$1对您不起作用,您可以使用此选项:

var pattern = new RegExp("amman", "i");
"abc Amman efg".replace(pattern, "<b>" + "abc Amman efg".match(pattern)[0] + "</b>");

您需要动态构建正则表达式,为此必须使用带有转义的新RegExp(字符串)构造函数。

jQuery UI自动完成小部件中有一个内置函数,名为$.UI.autocomplete.escapeRegex:

它将使用单个字符串参数并转义所有正则表达式字符,使结果安全地传递给新的RegExp()。

如果不使用jQuery UI,则可以从源复制其定义:

function escapeRegex( value ) {
    return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}

然后这样使用:

"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"

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

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

此外,当涉及到\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

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

这:

var txt=new RegExp(pattern,attributes);

相当于:

var txt=/pattern/attributes;

看见http://www.w3schools.com/jsref/jsref_obj_regexp.asp.