Are /regex/ Literals always RegExp Objects?

后端 未结 3 1037
南方客
南方客 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: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.

提交回复
热议问题