Range out of order in character class in javascript

Solution 1:

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_-.])+@