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

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

但我想这样做:

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

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


当前回答

this.replace( new RegExp( replaceThis, 'g' ), withThis );

其他回答

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

一种实现方法是从一个文本字段中获取值,该文本字段是您要替换的文本字段,另一种是“替换为”文本字段,从变量中的文本字段获取值,并将变量设置为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函数中传递一个变量。

当有一个简单得多的答案仍然可以使用正则表达式完成任务时,所有这些答案看起来都非常复杂。

String.prototype.replaceAll = function(replaceThis, withThis) {
    const expr = `${replaceThis}`
    this.replace(new RegExp(expr, "g"), withThis);
};

解释

RegExp构造函数接受两个参数:表达式和标志。通过在表达式中使用模板字符串,我们可以将变量传递到类中,它会将其转换为/(replaceThis变量的值)/g。

可以将字符串用作正则表达式。别忘了使用新的RegExp。

例子:

var yourFunction = new RegExp(
        '^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
      )