Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Extract Email Addresses from a String
Next article icon

JavaScript Program to Extract Email Addresses from a String

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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:

Table of Content

  • Using Regular Expressions
  • Splitting and Filtering
  • Using String Matching and Validation
  • Using a Custom Parser
  • Using the match Method with Regular Expressions

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)); 

Output
[ '[email protected]' ] 

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));  

Output
[ 'My', 'email', 'address', 'is', '[email protected]' ] 

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)); 

Output
[ '[email protected]' ] 

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]"));  

Output
[ '[email protected]', '[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]"] 

Output
[ '[email protected]', '[email protected]', '[email protected]' ] 



Next Article
JavaScript Program to Extract Email Addresses from a String

N

nikhilgarg527
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences