3

var str = "[email protected]"; // true but coming false
var str1 = "[email protected]"; 
var str2 = "[email protected]";
var str3 = "[email protected]";
var patt = new RegExp("[a-z0-9._%+-]+@[a-z0-9.-]+?[\.com]?[\.org]?[\.co.uk]?[\.org.uk]$");
console.log( str + " is " + patt.test(str));
console.log( str1 + " is " + patt.test(str1));
console.log( str2 + " is " + patt.test(str2));
console.log( str3 + " is " + patt.test(str3));

Can anyone tell me what is the mistake, my .com example is not working properly

2
  • You need a grouping construct and a regex literal, var patt = /^[a-z0-9._%+-]+@[a-z0-9.-]+?(?:\.com|\.org|\.co\.uk|\.org\.uk)$/; Commented Aug 26, 2022 at 14:32
  • You should anchor the pattern with ^ at the beginning. Commented Aug 26, 2022 at 15:01

1 Answer 1

0

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

var patt = /^[a-z0-9._%+-]+@[a-z0-9.-]+?(?:\.com|\.org|\.co\.uk|\.org\.uk)$/;

See the regex demo.

If you need to make it case insensitive, add i flag,

var patt = /^[a-z0-9._%+-]+@[a-z0-9.-]+?(?:\.com|\.org|\.co\.uk|\.org\.uk)$/i;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.