How to Check if a String is Available in Array in Javascript
In this tutorial, you will learn how to check if a string is available in array in javascript. In an array, we can have duplicate strings, and to keep our array filled with unique strings, we need to verify if a string is already present in it or not.
There are numerous ways to check if a string is available in an array. 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 element and check if the string is available in an array. 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
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Check”
and for theh1
element is“Result”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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
, andinput
elements using thedocument.querySelector()
method and stored them inbtnCheck
,result
, andinput
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are taking the value of the
input
element and passing it to theincludes()
method. This method will check if the string is available in the array. As a result, we will get a Boolean value in return. Depending upon that, we will displayTrue
orFalse
in theh1
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'; });