Js Regex Freezes My Browser(s)
Solution 1:
Use RegExp literal instead of RegExp constructor:
/(?=^(?:[A-Za-z0-9_\xC0-\xFF!#$%&'*+\/=?^`{|}~\\-]\.?){0,63}[A-Za-z0-9_\xC0-\xFF!#$%&'*+\/=?^`{|}~\\-]@[A-Za-z0-9\xC0-\xFF](?:[A-Za-z0-9\xC0-\xFF-]{0,61}[A-Za-z0-9\xC0-\xFF])?(?:\.[A-Za-z\xC0-\xFF](?:[A-Za-z0-9\xC0-\xFF-]{0,61}[A-Za-z0-9\xC0-\xFF])?)*$)(?=^.{3,254}$)/
I have taken the liberty of removing excessive escaping inside the character class (in JavaScript, only ]
, \
needs escaping, ^
don't need escaping if it is not at the start of a character class, -
don't need escaping if it is at the end of a character class) and make all the capturing groups non-capturing (since you don't care about the captured content).
When you use RegExp constructor, you need to supply a string. You need to escape \
in order to specify it in a string literal; otherwise, it will be treated as an escape sequence in string and the \
will not reach the RegExp constructor.
You can copy and paste your string inside the RegExp constructor in the console of your browser. On Firefox 34.0:
"(?=^([A-Za-z\xC0-\xFF0-9\!\#\$\%\&\'\*\+\-\/\=\?\^\\_\`\{\|\}\~]\.?){0,63}[A-Za-z\xC0-\xFF0-9\!\#\$\%\&\'\*\+\-\/\=\?\^\\_\`\{\|\}\~]@[A-Za-z\xC0-\xFF0-9]([A-Za-z\xC0-\xFF0-9-]{0,61}[A-Za-z\xC0-\xFF0-9])?(\.[A-Za-z\xC0-\xFF]([A-Za-z\xC0-\xFF0-9-]{0,61}[A-Za-z\xC0-\xFF0-9])?)*$)(?=^.{3,254}$)">>>"(?=^([A-Za-zÀ-ÿ0-9!#$%&'*+-/=?^\_`{|}~].?){0,63}[A-Za-zÀ-ÿ0-9!#$%&'*+-/=?^\_`{|}~]@[A-Za-zÀ-ÿ0-9]([A-Za-zÀ-ÿ0-9-]{0,61}[A-Za-zÀ-ÿ0-9])?(.[A-Za-zÀ-ÿ]([A-Za-zÀ-ÿ0-9-]{0,61}[A-Za-zÀ-ÿ0-9])?)*$)(?=^.{3,254}$)"
While it is not a problem for most of the parts, +-/
forms a character range in the character class, which includes ,
and .
(characters not intended to be in the class). And you get the dot-all .
instead of literal dot, which is the reason for catastrophic backtracking here:
(.[A-Za-zÀ-ÿ]([A-Za-zÀ-ÿ0-9-]{0,61}[A-Za-zÀ-ÿ0-9])?)*
Basing on the RegExp literal above, the equivalent code using RegExp constructor is:
new RegExp("(?=^(?:[A-Za-z0-9_\xC0-\xFF!#$%&'*+/=?^`{|}~\\\\-]\\.?){0,63}[A-Za-z0-9_\xC0-\xFF!#$%&'*+/=?^`{|}~\\\\-]@[A-Za-z0-9\xC0-\xFF](?:[A-Za-z0-9\xC0-\xFF-]{0,61}[A-Za-z0-9\xC0-\xFF])?(?:\\.[A-Za-z\xC0-\xFF](?:[A-Za-z0-9\xC0-\xFF-]{0,61}[A-Za-z0-9\xC0-\xFF])?)*$)(?=^.{3,254}$)")
Note that all \
are doubled up compared to the RegExp literal.
There is no reason to use the RegExp constructor, though. It should only be used when you need to generate regex based on some input. Fixed regex should be specified as RegExp literal.
Solution 2:
You can use this one. it will support after [dot] 2 ,3 character as per your domain
var email_filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (email_filter.test('yourEmail@gmail.com')) {
alert('Email is valid');
}
Post a Comment for "Js Regex Freezes My Browser(s)"