How to Check if a String Contains an Email Address in Javascript

In this tutorial, you will learn how to check if a string contains an email address in javascript. An email address is the first choice of contact if you want to get in touch with somebody over the internet. Before extracting an email address from a string, it is very important to validate it first. From a developer perspective, it can be a bit tricky to find if a string contains an email address.

An email consists of 3 parts. The first part can have random text, numbers, or special symbols such as underscores, dots, etc. The second and third part includes @ symbol and a domain name respectively.

There are numerous ways to check if a string contains an email address. But for the sake of simplicity, we will use email-validator library. Please copy the code given below, paste it in the javascript file and save it as email.js

In the following example, we have one global variable that holds a string. Upon click of a button, we will check if it contains an email address and display the result on the screen.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Check” and for the h1 element, it is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have included the email.js file using script tag which will help us in the email validation process.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>

  <div class="container">    
    <button>Check</button>
    <h1>Result</h1>
  </div>
  <script src="email.js"></script>
  <script src="script.js"></script>
</body>

</html>
.container {        
    text-align: center;
}

button {
  margin-top: 10px;
  padding: 10px 20px;
}

Javascript

  • We have selected the button element and h1 element using the document.querySelector() method and stored them in btnCheck and output variables respectively.
  • We have attached a click event listener to the button element.
  • We have a global variable myString which holds a string as its value.
  • In the event handler function, we are calling split() method to split myString into an array of strings and storing that array in strArray variable.
  • We are calling some() method to loop through each string in the array. In the anonymous function, we are calling ValidateEmail() method and passing the string as a parameter. This method is part of our email.js file and will return a Boolean value after validation.
  • After the completion, some() method will return either true or false. We are storing that in the found variable. If it is true, that means myString does contain an email address.
  • Depending upon the result of the check, we will assign “Yes” or “No” to the result variable.
  • We are displaying the result in the h1 element using the innerText property.

Email.js

var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;

function validateEmail(email)
{
    if (!email)
        return false;
        
    if(email.length>254)
        return false;

    var valid = tester.test(email);
    if(!valid)
        return false;

    // Further checking of some things regex can't handle
    var parts = email.split("@");
    if(parts[0].length>64)
        return false;

    var domainParts = parts[1].split(".");
    if(domainParts.some(function(part) { return part.length>63; }))
        return false;

    return true;
}

Script.js

let btnCheck = document.querySelector("button");
let output = document.querySelector("h1");

let myString = "To contact James, please send an email at james@example.com";

btnCheck.addEventListener("click", () => {
  let strArray = myString.split(" ");
  let found = strArray.some((str) => validateEmail(str));
  let result = found ? "Yes" : "No";
  output.innerText = result;
});