Check if a string contains an email address? [dupl

2019-05-03 11:16发布

This question already has an answer here:

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.

3条回答
Emotional °昔
2楼-- · 2019-05-03 11:26

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.

查看更多
何必那么认真
3楼-- · 2019-05-03 11:30

Try

/\b[a-z0-9-_.]+@[a-z0-9-_.]+(\.[a-z0-9]+)+/i.test(text)
查看更多
不美不萌又怎样
4楼-- · 2019-05-03 11:35

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);
}
查看更多
登录 后发表回答