10

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 a@b.xyz is present.

Example string:

Overall I liked the service, but had trouble using the widget generator.

Want more info? You can contact me at bob@example.org.

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.

Jim G.
  • 15,141
  • 22
  • 103
  • 166
Shpigford
  • 24,748
  • 58
  • 163
  • 252
  • 2
    What @WesleyMurch said. I'm looking for javascript here. Not PHP. – Shpigford May 07 '13 at 17:06
  • @WesleyMurch Ah bullocks, my bad :( but regular expressions work in JavaScript too. – Ja͢ck May 07 '13 at 17:07
  • 1
    FWIW, this post is already #1 in Google for "[javascript check if a string contains an email address](https://www.google.com/search?q=javascript+check+if+a+string+contains+an+email+address)". A good answer would be helpful, rather than dismissing the question because it's sort of related to another one. – Wesley Murch May 07 '13 at 17:07
  • You could also check out [this answer](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links/7123542#7123542) – Ja͢ck May 07 '13 at 17:09
  • Regular expressions aside, this is a Javascript question with a prominent php reference.... triggered! – Kickaha Oct 26 '17 at 13:42

3 Answers3

16

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);
}
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • On the negative of this it doesn't match new lines, any ideas how to amend this? https://regex101.com/r/rN6eD6/1 – Jimmyt1988 May 20 '15 at 23:43
8

You can use this:

var StrObj = "whatever, this is my email dave@gmail.com 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.

ed209
  • 828
  • 2
  • 14
  • 30
dave
  • 62,300
  • 5
  • 72
  • 93
  • this won't work at least for cyrilic email addresses, maybe for some other as well. e.g. emails from this domain - https://админ.com – Sam Tyurenkov Apr 28 '20 at 20:43
1

Try

/\b[a-z0-9-_.]+@[a-z0-9-_.]+(\.[a-z0-9]+)+/i.test(text)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531