Use JavaScript to find email address in a string?
Use the match method with a regular expression to extract email from a string in JavaScript.
Simple RegEx to extract email address from string
/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/
Note: It will match not match 100% of the email patterns.
Example of JavaScript extract email from string
In the example, we created a function with regex /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/ to extract email ids (address) from the long text.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
// function for get email id
function extractEmails ( text ){
return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/gi);
}
//test
alert(extractEmails('Hi, contact on [email protected]'))
</script>
</head>
<body>
</body>
</html>
Output:
Here’s the decomposition of the regex /<(.*)>/
:
/
and/
are mandatory to define a regex<
and>
simply matches the two<
and>
in your string()
parenthesis “capture” what you’re looking for. Here, they get the mail address inside.- .* : . means “any character”, and * means “any number of times. Combined, it means “any character any number of times”, and that is inside < and >, which corresponds to the place where the mail is.
Q: How to Extract all email addresses from bulk text using JS?
Answer: Here is HTML example code with easy approach:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var text = '[email protected], "assdsdf" <[email protected]>,
"cook son" <[email protected]>, "Stark joe" <[email protected]>,
"Ronal techno" <[email protected]>, "Boo ke" <[email protected]>,
"aki same" <[email protected]>, "Praksh Tom" <[email protected]>,;
"mini sen" <[email protected]>';
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
console.log(extractEmails(text).join('\n'));
</script>
</head>
<body>
<p id="emails"></p>
</body>
</html>
Do comment if you have any doubts and suggestion with code in this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Your article help me to make a email extractor.
thanks you very much
Thanks Rohit, this code certainly worked in my case