Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegEx to determine the email's domain (yahoo.com for example)

With JavaScript I want to take a input 1st validate that the email is valid (I solved for this) 2nd, validate that the email address came from yahoo.com

Anyone know of a Regex that will deliver the domain?

thxs

like image 646
AnApprentice Avatar asked Jul 17 '10 03:07

AnApprentice


3 Answers

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).

like image 152
Tim Pietzcker Avatar answered Oct 25 '22 23:10

Tim Pietzcker


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.

like image 29
styfle Avatar answered Oct 25 '22 21:10

styfle


function emailDomainCheck(email, domain)
{
    var parts = email.split('@');
    if (parts.length === 2) {
        if (parts[1] === domain) {
            return true;
        }
    }
    return false;
}

:)

like image 36
Vũ Nhật Anh Avatar answered Oct 25 '22 21:10

Vũ Nhật Anh