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

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

但我想这样做:

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

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


当前回答

此自调用函数将使用索引遍历replacerItems,并在每次传递时全局更改字符串上的replacerItem[index]。

  const replacerItems = ["a", "b", "c"];    

    function replacer(str, index){
          const item = replacerItems[index];
          const regex = new RegExp(`[${item}]`, "g");
          const newStr = str.replace(regex, "z");
          if (index < replacerItems.length - 1) {
            return replacer(newStr, index + 1);
          }
          return newStr;
    }

// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'

其他回答

还有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!"

虽然您可以创建动态创建的RegExp(根据对这个问题的其他回答),但我会在类似的帖子中重复我的评论:String.replace()的函数形式非常有用,在许多情况下减少了对动态创建RegExp对象的需要。(这是一种痛苦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜杠/[a-Z]+/RegExp文本格式)

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

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

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

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

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

“ABABAB”替换(/B/g,“A”);

一如既往:除非迫不得已,否则不要使用正则表达式。对于简单的字符串替换,习惯用法是:

'ABABAB'.split('B').join('A')

这样,您就不必担心Gracenotes的回答中提到的引用问题。