给正则表达式添加变量:
方法一: new RegExp
function replace(str, before, after) { var reg = new RegExp(before, "g"); return str.replace(reg, after); } var test = ; console.log(replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));
方法二: eval
function replace(str, before, after) { return str.replace(eval("/"+before+"/g"), after); } console.log(replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));