JavaScript
x
9
1
var str = "sdhdhh@gmail.com"; // true but coming false
2
var str1 = "sdhdhh@gmail.co.uk";
3
var str2 = "sdhdhh@gmail.org";
4
var str3 = "sdhdhh@gmail.org.uk";
5
var patt = new RegExp("[a-z0-9._%+-]+@[a-z0-9.-]+?[.com]?[.org]?[.co.uk]?[.org.uk]$");
6
console.log( str + " is " + patt.test(str));
7
console.log( str1 + " is " + patt.test(str1));
8
console.log( str2 + " is " + patt.test(str2));
9
console.log( str3 + " is " + patt.test(str3));
Can anyone tell me what is the mistake, my .com example is not working properly
Advertisement
Answer
You need
- A grouping construct instead of character classes
- A regex literal notation so that you do not have to double escape special chars
- The
^
anchor at the start of the pattern since you need both^
and$
to make the pattern match the entire string.
So you need to use
JavaScript
1
2
1
var patt = /^[a-z0-9._%+-]+@[a-z0-9.-]+?(?:.com|.org|.co.uk|.org.uk)$/;
2
See the regex demo.
If you need to make it case insensitive, add i
flag,
JavaScript
1
2
1
var patt = /^[a-z0-9._%+-]+@[a-z0-9.-]+?(?:.com|.org|.co.uk|.org.uk)$/i;
2