How to Check if a String is Present in an Array in Javascript

In this tutorial, you will learn how to check if a string is present in an array in javascript. In an array, we can have duplicate items, and to keep our array filled with unique items, we need to verify if an element is already present in it or not.

There are numerous ways to detect whether a string is present in an array or not. But for the sake of simplicity, we are going to use only the includes() method. This method returns true if the array contains the specified string, otherwise false.

In the following example, we have one global array users and it holds an array of strings.  We will simply take value from the input value and verify if it’s part of the array or not.  After verification, we will get a Boolean value in return and that will be displayed in the h1 element.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 4 elements in the HTML file (div, button, input, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element 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 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>
        <input type="text">
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

input,button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have a global variable users and it holds an array of strings.
  • We have selected button, h1, and input elements using the document.querySelector() method and stored them in btnCheck, result, and input variables respectively.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are taking the value of the input element and passing it to the includes() method. We will get a Boolean value in return. Depending upon that, we will display True or False in the h1 element.
let users = ['Peter', 'Mary', 'Marks', 'James', 'Ronald'];

let btnCheck = document.querySelector('button');
let input = document.querySelector('input');
let result = document.querySelector('h1');

btnCheck.addEventListener('click', () => {
 result.innerText = users.includes(input.value) ? 'True' : 'False';
});