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.
To check if a string is a valid email address in JavaScript, we can use a regex expression to match the symbols like @ , . and the strings in between them.
The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.
You can perform a PHP validation email by using the filter_var() function and passing the given email and filter id “FILTER_VALIDATE_EMAIL” as arguments.
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);
}
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.
Try
/\b[a-z0-9-_.]+@[a-z0-9-_.]+(\.[a-z0-9]+)+/i.test(text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With