Check if a string contains an email address?

16,045

Solution 1

Debuggex Example

JsFiddle Example

function checkIfEmailInString(text) { 
    var re = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
    return re.test(text);
}

Solution 2

You can use this:

var StrObj = "whatever, this is my email [email protected] other text";
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (emailsArray != null && emailsArray.length) {
    //has email
}

This also lets you get the email address from the array, if you need it.

Solution 3

Try

/\b[a-z0-9-_.]+@[a-z0-9-_.]+(\.[a-z0-9]+)+/i.test(text)
Share:
16,045
Shpigford
Author by

Shpigford

Maker. Dabbler. Founder of Baremetrics. I can't stop starting things. Cedar &amp; Sail, Laser Tweets, Founder Chats, Droptune, Rockburg. Bearded.

Updated on July 28, 2022

Comments

  • Shpigford
    Shpigford almost 2 years

    How can I check to verify that a given string contains an email address.

    The email address would be included with a lot of other text, as well.

    Also, not looking to necessarily strictly validate the email address itself. More so just wanting to make sure that [email protected] is present.

    Example string:

    Overall I liked the service, but had trouble using the widget generator.
    
    Want more info? You can contact me at [email protected].
    

    Plain javascript is fine, but I do happen to be using jQuery, so if there's some sort of helper function that makes this easier...go for it.

  • Jimmyt1988
    Jimmyt1988 almost 9 years
    On the negative of this it doesn't match new lines, any ideas how to amend this? regex101.com/r/rN6eD6/1
  • Sam Tyurenkov
    Sam Tyurenkov about 4 years
    this won't work at least for cyrilic email addresses, maybe for some other as well. e.g. emails from this domain - админ.com