What is the difference between using “new RegExp” and using forward slash notation to create a regular expression?

前端 未结 4 771
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:46

Is there any difference between using new RegExp(\"regex\"); and /same_regex/ to test against a target string? I am asking this question because I

4条回答
  •  遥遥无期
    2020-12-06 05:30

    /.../ is called a regular expression literal. new RegExp uses the RegExp constructor function and creates a Regular Expression Object.

    From Mozilla's developer pages

    Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

    Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

提交回复
热议问题