Open In App

JavaScript Program to Extract Email Addresses from a String

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Approach 1: 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.

Javascript




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' ]

Approach 2: 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.

Javascript




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' ]

Approach 3: 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.

Javascript




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' ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads