javascript 检查字符串是否包含电子邮件地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16424659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string contains an email address?
提问by Shpigford
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.
此外,不必严格验证电子邮件地址本身。更何况只是想确保[email protected]
存在。
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.
普通的 javascript 很好,但我碰巧在使用 jQuery,所以如果有某种帮助函数可以使这更容易......去吧。
回答by KingKongFrog
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);
}
回答by dave
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.
如果需要,这还可以让您从数组中获取电子邮件地址。
回答by Arun P Johny
Try
尝试
/\b[a-z0-9-_.]+@[a-z0-9-_.]+(\.[a-z0-9]+)+/i.test(text)