JavaScript Program to Extract Email Addresses from a String
Last Updated : 10 Jul, 2024
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:
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 [email protected]"; console.log(extract(str));
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 [email protected]"; console.log(extract(str));
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 [email protected]"; console.log(extract(str));
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.
JavaScript 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 [email protected] and [email protected]"));
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.
JavaScript 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 [email protected], [email protected], or [email protected] for more information."; let emailAddresses = extractEmailsUsingMatch(inputString); console.log(emailAddresses); // Output: ["[email protected]", "[email protected]", "[email protected]"]
Similar Reads
How to Validate Email Address using RegExp in JavaScript? Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.Why Validate Email Addresses?Validating email addresses is important for a number of reasons
3 min read
How to Validate Email Address without using Regular Expression in JavaScript ? Email validation in JavaScript is the process of ensuring that an email address entered by the user is in the correct format and is a valid email address or not. This is typically done on the client side using JavaScript before the form is submitted to the server.An email address must have the follo
5 min read
Java Program to Extract Content from a HTML document HTML is the core of the web, all the pages you see on the internet are HTML, whether they are dynamically generated by JavaScript, JSP, PHP, ASP, or any other web technology. Your browser actually parses HTML and render it for you But if we need to parse an HTML document and find some elements, tags
4 min read
How to Extract Text before @ Sign from an Email Address in Excel? You got a dataset and you want to extract the name part of the email address. This task can be done with a text to column and formula that uses the LEFT and FIND functions. Using LEFT and FIND functionsThe LEFT function: The LEFT function returns a given text from the left of our text string based o
3 min read
Extract a Substring Between Two Characters in a String in Java In Java, the extraction of the substring between the two characters in a string can be implemented with the substring method, and string is a pre-defined method in the class of the String. A String is a pre-defined class of the java.lang package. substring(startIndex, endIndex): This is a pre-define
2 min read