Skip to content

JavaScript array contains string

  • by

JavaScript array can contain strings. You can check if a string array contains a particular string in JavaScript using the includes() method.

myArray.includes('str')

JavaScript array contains string example

Simple example code.

<!DOCTYPE html>
<html>
  <body>
    <script>
        const myArray = ['apple', 'banana', 'cherry'];

        if (myArray.includes('banana')) {
            console.log('The array contains "banana"');
        } else {
            console.log('The array does not contain "banana"');
        }

    </script>
  </body>
</html>

Output:

JavaScript array contains string

You can also use the indexOf() method to check if a string is in an array. This method returns the index of the first occurrence of the string in the array, or -1 if the string is not found. Here’s an example:

const myArray = ['apple', 'banana', 'cherry'];

if (myArray.indexOf('banana') !== -1) {
  console.log('The array contains "banana"');
} else {
  console.log('The array does not contain "banana"');
}

Or you can create a function for it

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading