我想在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!"

其他回答

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

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

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

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

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

如果要获取所有出现的单词(g),请区分大小写(i),并使用边界,使其不是另一个单词中的单词(\\b):

re = new RegExp(`\\b${replaceThis}\\b`, 'gi');

let inputString=“我是John或johnny,但我更喜欢John。”;let replaceThis=“John”;let re=新RegExp(`\\b${replaceThis}\\b`,'gi');console.log(inputString.replace(re,“Jack”));

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

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

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

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

您始终可以重复使用indexOf:

String.prototype.replaceAll = function(substring, replacement) {
    var result = '';
    var lastIndex = 0;

    while(true) {
        var index = this.indexOf(substring, lastIndex);
        if(index === -1) break;
        result += this.substring(lastIndex, index) + replacement;
        lastIndex = index + substring.length;
    }

    return result + this.substring(lastIndex);
};

当替换包含匹配项时,这不会进入无限循环。