JavaScript RegEx to determine the email's domain (yahoo.com for example)
var myemail = '[email protected]'
if (/@yahoo.com\s*$/.test(myemail)) {
console.log("it ends in @yahoo");
}
is true if the string ends in @yahoo.com
(plus optional whitespace).
You do not need to use regex for this.
You can see if a string contains another string using the indexOf
method.
var idx = emailAddress.indexOf('@yahoo.com');
if (idx > -1) {
// true if the address contains yahoo.com
}
We can take advantage of slice()
to implement "ends with" like so:
var idx = emailAddress.lastIndexOf('@');
if (idx > -1 && emailAddress.slice(idx + 1) === 'yahoo.com') {
// true if the address ends with yahoo.com
}
In evergreen browsers, you can use the built in String.prototype.endsWith() like so:
if (emailAddress.endsWith('@yahoo.com')) {
// true if the address ends with yahoo.com
}
See the MDN docs for browser support.
function emailDomainCheck(email, domain)
{
var parts = email.split('@');
if (parts.length === 2) {
if (parts[1] === domain) {
return true;
}
}
return false;
}
:)