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

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

但我想这样做:

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

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


当前回答

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

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

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

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

其他回答

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

例子:

var yourFunction = new RegExp(
        '^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
      )
this.replace( new RegExp( replaceThis, 'g' ), withThis );

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

这里是另一个replaceAll实现:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

示例:regex以开头

function startWith(char, value) {
    return new RegExp(`^[${char}]`, 'gi').test(value);
}