0

I am looking the consequences of using new RegExp() vs RegExp() in this scenario:

        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")));

I want to avoid creating the var build_rexp_from_var because it is unnecessary. Both seems to work, but I want to know the differences that might have using one over the other.

Gaph
  • 19
  • 3

1 Answers1

3

RegExp("foo") and new RegExp("foo") do the same thing:

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

In simpler terms, RegExp(/someRegex/) returns that regex, while RegExp("someString") creates a new regexp from the string, just as new RegExp does.

georg
  • 195,833
  • 46
  • 263
  • 351
  • ok, my conclusion is: use new if you are creating it to a var `var x = new RegExp(...);`. But if using it directly just use `RegExp(...)`, I saw one example of using it directly at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FRegExp#Example:_Using_a_regular_expression_with_the_sticky_flag – Gaph Sep 05 '13 at 18:34
  • The ECMAScript 7 spec is written in plainer English. From Section 21.2.3: "When RegExp is called as a function rather than as a constructor, it creates and initializes a new RegExp object. Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments." See http://www.ecma-international.org/ecma-262/7.0/index.html#sec-regexp-constructor. Consistently using the "new" keyword would seem to be better form since it makes clear what the return value is: a new RegExp object. – Patrick Dark Oct 01 '16 at 20:41