JavaScript Program to Extract Email Addresses from a String
In this article, we will explore how to extract email addresses from a string in JavaScript. Extracting email addresses from a given text can be useful for processing and organizing contact information.
There are various approaches to extract email addresses from a string in JavaScript:
Table of Content
Using Regular Expressions
Regular expressions provide an elegant way to match and extract email addresses from text.
Example: In this example, we will extract the substring that matches the given regular expression.
function extract(str) {
const email =
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
return str.match(email);
}
const str =
"My email address is info@geeksforgeeks.org";
console.log(extract(str));
Output
[ 'info@geeksforgeeks.org' ]
Splitting and Filtering
In this approach we will Split the string by space using str.split() method and then use filter() method filter out valid email formats.
Example: In this example, we will use split the string and filter out the required email substring.
function extract(str) {
const words = str.split(' ');
const valid = words.filter(word => {
return /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/.test(str);
});
return valid;
}
const str =
"My email address is info@geeksforgeeks.org";
console.log(extract(str));
Output
[ 'My', 'email', 'address', 'is', 'info@geeksforgeeks.org' ]
Using String Matching and Validation
In this approach, we will check each substring for email validity.
Example: In this example we will check the email validation for every substring and display the ouput.
function isValid(str) {
return /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/.test(str);
}
function extract(str) {
const words = str.split(' ');
const email = [];
for (const word of words) {
if (isValid(word)) {
email.push(word);
}
}
return email;
}
const str =
"My email address is info@geeksforgeeks.org";
console.log(extract(str));
Output
[ 'info@geeksforgeeks.org' ]
Using a Custom Parser
The custom parser approach iterates through words in the text, identifying email addresses by checking for the presence of '@' and '.' characters, and ensuring the structure resembles an email. This method is simple and doesn't rely on regex.
Example: The function extractEmails parses a text to find and return email addresses present within it. It searches for patterns containing '@' and '.', and returns them as an array.
function extractEmails(text) {
const emails = [];
const words = text.split(/\s+/);
for (let word of words) {
if (word.includes('@') && word.includes('.')) {
const parts = word.split('@');
if (parts.length === 2 && parts[1].includes('.')) {
emails.push(word);
}
}
}
return emails;
}
console.log(extractEmails("Contact us at info@GeeksforGeeks.com and support@domain.org"));
Output
[ 'info@GeeksforGeeks.com', 'support@domain.org' ]
Using the match Method with Regular Expressions
In this approach, we use JavaScript's match method combined with a regular expression specifically designed to capture email addresses. This method is efficient and straightforward for extracting all occurrences of email addresses from a given string.
Steps:
- Define the Regular Expression: Create a regular expression pattern that matches typical email addresses.
- Use the match Method: Apply the match method on the input string with the defined regular expression to extract all email addresses.
- Handle the Results: The result will be an array of email addresses or null if no matches are found.
Example: This example demonstrates how to extract email addresses from a string using the match method and regular expressions.
function extractEmailsUsingMatch(input) {
// Define a regular expression for matching email addresses
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
// Use the match method to find all email addresses in the input string
const matches = input.match(emailRegex);
// Return the array of matched email addresses or an empty array if no matches are found
return matches || [];
}
// Example usage:
let inputString = "Contact us at support@example.com, sales@example.co.uk, or admin@example.org for more information.";
let emailAddresses = extractEmailsUsingMatch(inputString);
console.log(emailAddresses); // Output: ["support@example.com", "sales@example.co.uk", "admin@example.org"]
Output
[ 'support@example.com', 'sales@example.co.uk', 'admin@example.org' ]