should I drop the 'new' in this function passing regexp?
本问题已经有最佳答案,请猛点这里访问。
我在这个场景中看到使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
15.10.3 The RegExp Constructor Called as a Function
15.10.3.1 RegExp(pattern, flags)
If pattern is an object R whose [[Class]] internal property is"RegExp" and flags is undefined, then return R unchanged. Otherwise call the standard built-in RegExp constructor (15.10.4.1) as if by the expression new RegExp( pattern, flags) and return the object constructed by that constructor.
http://es5.github.io/#x15.10.3
简单来说,