Are inline JavaScript regular expressions faster?

后端 未结 3 1617
醉梦人生
醉梦人生 2021-01-05 07:09

Is it better to use the RegExp object or the inline style? And why?

3条回答
  •  余生分开走
    2021-01-05 07:24

    As per J-P's answer there is a slight difference, which sometimes could be important. The intent was that:

    var re = /\d+/;
    

    be the same as:

    var re = new RegExp("\\d+");
    

    but, oddly, in Firefox/Chrome it isn't quite the same (as demonstrated by his example with stateful expressions that are used multiple times).

    So, use the RegExp object would be my advice. And an excellent find by J-P.

    That being said, the major circumstance where you had to use RegExp over the literal syntax anyway was to dynamically create expressions, for example:

    var s = "[asdf]+";
    var re = new RegExp(":" + s + ":", "g");
    

提交回复
热议问题