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

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

但我想这样做:

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

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


当前回答

我在这里和stackoverflow或类似论坛上的其他公开门票中找到了很多带有奇怪例子的答案。

这是我认为最简单的选项,如何将变量作为模板文本字符串;

const someString = "abc";
const regex = new RegExp(`^ someregex ${someString} someregex $`);

正如您所看到的,我没有在开头或结尾处使用正斜杠,RegExp构造函数将重建有效的正则表达式文字。还可以使用yup matches函数。

其他回答

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

“ABABAB”替换(/B/g,“A”);

一如既往:除非迫不得已,否则不要使用正则表达式。对于简单的字符串替换,习惯用法是:

'ABABAB'.split('B').join('A')

这样,您就不必担心Gracenotes的回答中提到的引用问题。

您可以构造一个新的RegExp对象,而不是使用/regex\d/g语法:

var replace = "regex\\d";
var re = new RegExp(replace,"g");

您可以通过这种方式动态创建正则表达式对象。然后您将执行以下操作:

"mystring1".replace(re, "newstring");

还有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!"
this.replace( new RegExp( replaceThis, 'g' ), withThis );