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

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

但我想这样做:

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

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


当前回答

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

其他回答

this.replace( new RegExp( replaceThis, 'g' ), withThis );
String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}

测试方式如下:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))

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

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

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

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

如果使用正确的语法传递变量,可以使用下面的代码这样做。

这还有一个额外的好处,就是在同一个变量中使用标志。

此外,当涉及到\w等时,您不必在正则表达式中进行双转义。

var str=“regexVariable示例:这是我用regexVariable替换RegExp的示例。”var reVar=/(.*?)(正则表达式\w+?able)(.+?)/gi;var resStr=str.replace(新RegExp(reVar),'$1:):):)$2:)::)$3');console.log(resStr);//退货://:):)::)regexVariable:):。

原型版本符合OP的示例:

var str=“regexVariable原型:这是我用regexVariable替换RegExp的示例。”String.prototype.regexVariable=函数(reFind,reReplace){return str.replace(新RegExp(reFind),reReplace);}var reVar=/(.*?)(正则表达式\w+?able)(.+?)/gi;console.log(str.regexVariable(reVar,‘$1:):):)$2:)::)$3'));//退货://:):)::)regexVariable:):。

正如埃里克·温德林提到的,你可以这样做:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

这会产生“正则表达式匹配”。然而,如果str1为“.”,则会失败。您可能希望结果是“模式匹配正则表达式”,将句点替换为“正则表达式”。但结果是。。。

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

这是因为,尽管“.”是一个字符串,但在RegExp构造函数中,它仍然被解释为正则表达式,表示任何非换行字符,表示字符串中的每个字符。为此,以下功能可能有用:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };

然后您可以执行以下操作:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

产生“模式匹配正则表达式”。