我想在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字符串?
我知道有很多这样的话题.我知道基础知识:.forEach()在原始数组和.map()新数组上运行.
就我而言:
function practice (i){
return i+1;
};
var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);
Run Code Online (Sandbox Code Playgroud)
这是输出:
[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ] …Run Code Online (Sandbox Code Playgroud)