How to Check if Array Contains Specific String in Javascript
In this tutorial, you will learn how to check if array contains specific string in javascript. An array is just a collection of type agnostic elements. 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 an array contains specific string. 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. Upon click of a button, we will check if the array contains specific string. Please have a look over the code example and steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, 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> <button>Check</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } 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
andh1
elements using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are passing an empty string to the
includes()
method. This method will check if the array contains a specific string"James"
. - As a result, we will get a Boolean value in return. Depending upon that, we will display
True
orFalse
in theh1
element.
let users = ['Peter', 'Mary', 'Marks', 'James', 'Ronald']; let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); btnCheck.addEventListener('click', () => { result.innerText = users.includes('James') ? 'True' : 'False'; });