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

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

但我想这样做:

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

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


当前回答

为了满足我在正则表达式中插入变量/别名/函数的需要,我想到了以下方法:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");

其中“oldre”是我要插入变量的原始正则表达式,“xx”是该变量/别名/函数的占位符,“yy”是实际变量名、别名或函数。

其他回答

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

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

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

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

这里是另一个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;
    };

对于不带正则表达式的多重替换,我使用了以下方法:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

解决方案的重要部分在这里找到

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

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

解释

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

这些答案我都不清楚

简单的答案是:

var search_term = new RegExp(search_term, "g");
text = text.replace(search_term, replace_term);

例如:

$(“button”).click(函数){查找和替换(“Lorem”、“Chocolate”);查找和替换(“ipsum”,“冰淇淋”);});函数Find_andreplace(搜索_时间段,替换_时间段){text=$(“textbox”).html();var search_term=新RegExp(search_term,“g”);text=text.replace(搜索时间,替换时间);$(“textbox”).html(文本);}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><文本框>Lorem ipsum</textbox><button>单击我</button>