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

前端 未结 4 768
佛祖请我去吃肉
佛祖请我去吃肉 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:29

    Difference is in escaping at least in your case. When you use / / notation, you have to escape '/' with '\/', when you're using Regexp notation you escape quotes

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 05:50

    If you use the constructor to create a new RegExp object instead of the literal syntax, you need to escape the \‍ properly:

    new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")
    

    This is necessary as in JavaScript any unknown escape sequence \x is interpreted as x. So in this case the \. is interpreted as ..

    0 讨论(0)
  • 2020-12-06 05:50

    this will be a help for you http://www.regular-expressions.info/javascript.html see the 'How to Use The JavaScript RegExp Object' section

    if you are using RegExp(regx) regx should be in string format ex:- \w+ can be created as regx = /\w+/ or as regx = new RegExp("\\w+").

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