Are /regex/ Literals always RegExp Objects?

后端 未结 3 1031
南方客
南方客 2020-12-19 02:55

Basically, my question is about how Javascript handles regex literals.

Contrasting with number, string and boolean where literals are primitive data types and corres

相关标签:
3条回答
  • 2020-12-19 03:28

    Here's what the spec has to say:

    A regular expression literal is an input element that is converted to a RegExp object when it is scanned. The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object. Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical.

    There is no primitive regex type that autoboxes to an object in the same way as string or number.

    Note, however, that not all browsers implement the "instantiate-once-per-literal" behavior, including Safari and IE6 (and possibly later), so portable code shouldn't depend on it. The abortive ECMAScript 4 draft would have changed the behavior to match those browsers:

    In ES3 a regular expression literal like /a*b/mg denotes a single unique RegExp object that is created the first time the literal is encountered during evaluation. In ES4 a new RegExp object is created every time the literal is encountered during evaluation.

    Also, some browsers (Firefox <3, Safari) report typeof /regex/ as "function", so portable code should avoid typeof on RegExp instances—stick with instanceof.

    0 讨论(0)
  • 2020-12-19 03:39

    Yes, new RegExp("something", "g") is the same as /something/g

    0 讨论(0)
  • 2020-12-19 03:43

    Yes, the following two expressions are equivalent:

    var r1 = /ab+c/i,
        r2 =new RegExp("ab+c", "i");
    

    The constructor property of both points to the RegExp constructor function:

    (/ab+c/i).constructor === RegExp // true
    r2.constructor === RegExp // true
    

    And a regexp literal is an instance of RegExp:

     /ab+c/i instanceof RegExp // true
    

    The basic difference is that defining regular expressions using the constructor function allows you to build and compile an expression from a string. This can be very useful for constructing complex expressions that will be re-used.

    0 讨论(0)
提交回复
热议问题