如何在正则表达式中使用变量?

我想String.replaceAll()在 JavaScript 中创建一个方法,我认为使用正则表达式是最简洁的方法。但是,我不知道如何将变量传递给正则表达式。我已经可以这样做了,这将替换"B"with 的所有实例"A"。

"ABABAB".replace(/B/g, "A");
但我想做这样的事情

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

但显然这只会替换文本"replaceThis" 那么我如何将此变量传递给我的正则表达式字符串?

/regex\d/g您可以构造一个新的RegExp对象,而不使用语法:
var replace = "regex\d";
var re = new RegExp(replace,"g");

您可以通过这种方式动态创建正则表达式对象。然后你会做:
"mystring1".replace(re, "newstring");