我正在寻找在这种情况下使用new RegExp()
vs的后果:RegExp()
function removeWord(str,rexp){
return str.replace(rexp,"")
}
var example1="I like tasty peanuts!";
var banned_word="peanuts";
var build_rexp_from_var=new RegExp(banned_word,"g");
//method #1 -> removeWord(example1,/peanuts/g)
//method #2 -> removeWord(example1,build_rexp_from_var)
//which should be my method #3?
console.log(removeWord(example1,RegExp(banned_word,"g")));
console.log(removeWord(example1,new RegExp(banned_word,"g")));
我想避免创建 var build_rexp_from_var
,因为它是不必要的。两者似乎都有效,但我想知道使用其中一个可能存在的差异。