I would like to create a String.replaceAll()
method in JavaScript and I'm thinking that using a regex would be most terse way to do it.(我想在JavaScript中创建String.replaceAll()
方法,并且我认为使用正则表达式是最简洁的方法。)
"B"
with "A"
.(我已经可以这样做了,它将用"A"
替换"B"
所有实例。)
"ABABAB".replace(/B/g, "A");
But I want to do something like this:(但是我想做这样的事情:)
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
But obviously this will only replace the text "replaceThis"
...so how do I pass this variable in to my regex string?(但是显然,这只会替换文本"replaceThis"
...所以如何将这个变量传递给我的正则表达式字符串?)