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

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

但我想这样做:

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

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


当前回答

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

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:):。

您需要动态构建正则表达式,为此必须使用带有转义的新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]"

还有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!"

一种实现方法是从一个文本字段中获取值,该文本字段是您要替换的文本字段,另一种是“替换为”文本字段,从变量中的文本字段获取值,并将变量设置为RegExp函数以进一步替换。在我的例子中,我使用的是jQuery,但您也可以只使用JavaScript来实现。

JavaScript代码:

  var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
  var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.

  var sRegExInput = new RegExp(replace, "g");
  $("body").children().each(function() {
    $(this).html($(this).html().replace(sRegExInput,replace_with));
  });

此代码位于按钮的Onclick事件上,您可以将其放在要调用的函数中。

现在可以在replace函数中传递一个变量。

虽然您可以创建动态创建的RegExp(根据对这个问题的其他回答),但我会在类似的帖子中重复我的评论:String.replace()的函数形式非常有用,在许多情况下减少了对动态创建RegExp对象的需要。(这是一种痛苦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜杠/[a-Z]+/RegExp文本格式)