Range out of order in character class in javascript

前端 未结 1 900
星月不相逢
星月不相逢 2020-12-05 06:36

I don\'t know why my regex is incorrect:

var domain = \"google\\.com\\.br\";
var reEmail = new RegExp(\"^([A-Za-z0-9_\\-\\.])+\\@\" + domain + \"$\");


        
相关标签:
1条回答
  • 2020-12-05 07:01

    Because you create the RegExp using a String the _\-\. becomes _-. and that is the invalid range. (It is a range from _ to . and that is not correct)

    You need to double escape it:

    new RegExp("^([A-Za-z0-9_\\-\\.])+@" + domain + "$");
    

    That way the \\ becomes a \ in the String and then is used to escape the -in the RegExp.

    EDIT:

    If you create RegExp by String it is always helpful to log the result so that you see if you did everything right:

    e.g. your part of the RegExp

    console.log("^([A-Za-z0-9_\-\.])+\@");
    

    results in:

    ^([A-Za-z0-9_-.])+@
    
    0 讨论(0)
提交回复
热议问题