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

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

但我想这样做:

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

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


当前回答

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("]", ">"))

其他回答

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

示例:regex以开头

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

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

例子:

var yourFunction = new RegExp(
        '^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
      )

对于任何希望在匹配方法中使用变量的人来说,这对我很有用:

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

如果要获取所有出现的单词(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”));