关于javascript:我应该通过regexp删除此函数中的’new’吗?

should I drop the 'new' in this function passing regexp?

本问题已经有最佳答案,请猛点这里访问。

我在这个场景中看到使用new RegExp() vs 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 build_rexp_from_var因为它是不必要的。 两者似乎都有效,但我想知道使用一个而不是另一个可能产生的差异。


RegExp("foo")new RegExp("foo")做同样的事情:

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

简单来说,RegExp(/someRegex/)返回正则表达式,而RegExp("someString")从字符串创建一个新的正则表达式,就像new RegExp一样。