Check if user inputted string is in the array in JavaScript


We are required to write a JavaScript program that provides the user an input to enter a string value.

The program should then check the input value against some hard-coded array values. Our program should print true to the screen if the input string value is included in the array, false otherwise.

Example

The code for this will be −

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>CHECK EXISTENCE</title>
</head>
<body>
   <script>
      const arr = ['arsenal', 'chelsea', 'everton', 'fulham',
      'swansea'];
      const checkExistence = () => {
         const userInput = document.getElementById("input").value;
         const exists = arr.includes(userInput);
         document.getElementById('result').innerText = exists;
      };
   </script>
   <input type="text" id="input">
   <button onclick="checkExistence()">Check</button>
   <p id='result'></p>
</body>
</html>

Output

And the output on the screen will be −

Updated on: 20-Nov-2020

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements