我想在JavaScript中创建一个String.replaceAll()方法,我认为使用RegEx将是最简洁的方法.但是,我无法弄清楚如何将变量传递给RegEx.我已经可以做到这一点,它将用"A"替换所有"B"的实例.
"ABABAB".replace(/B/g, "A");
Run Code Online (Sandbox Code Playgroud)
但我想做这样的事情:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
Run Code Online (Sandbox Code Playgroud)
但显然这只会替换文本"replaceThis"...所以如何将此变量传递给我的RegEx字符串?
如何使用与变量匹配在两个字符串之间获取字符串?如果我使用匹配字符串正则表达式来获取Javascript中的两个字符串之间的字符串 我也尝试在JavaScript中应用信息- 在字符串匹配中使用变量:
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)
但如果我有:
var firstvariable = "cow";
var secondvariable = "milk";
var test = "My cow always gives milk";
Run Code Online (Sandbox Code Playgroud)
我尝试过各种各样的事情,包括:
var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)
和:
var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)
都没有奏效.