7
What is the reason for the result divergence found when executing the same regular expression in different ways in Javascript?
Regular expression:
^([a-z][a-z0-9]{0,30}\.)?((?!\d+\.)[a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)(\.[a-z]{2,4}(?:\.[a-z]{2})?)$
Method 1 (works properly):
function valida_dominio(value){
return /^([a-z][a-z0-9]{0,30}\.)?((?!\d+\.)[a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)(\.[a-z]{2,4}(?:\.[a-z]{2})?)$/.test(value);
}
Method 2 (not functioning properly):
function valida_dominio(value){
let str_pattern = '^([a-z][a-z0-9]{0,30}\.)?((?!\d+\.)[a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)(\.[a-z]{2,4}(?:\.[a-z]{2})?)$';
let pattern = new RegExp(str_pattern, "i");
return pattern.test(value);
}
The goal of method 2 is to pass regular expression as a string. But it does not work properly. For example:
- approves the domain "cëa.br" which is invalid;
- approves the domain "26characters-asdfasdfa.com.br" which is valid.
How to make method 2 work properly? That is, how to pass the regular expression via string without having divergence in the result?
OBS: No Regexp and in method 1 the regular expression works correctly.
Another difference, beyond the question of
\
, is the flagi
method 2. By default,[a-z]
only consider lower case letters, but with the flagi
regex will also pick up uppercase letters– hkotsubo