Check if String contains Substring from Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if String contains Substring from an Array #

To check if a string contains a substring from an array:

  1. Use the Array.some() method to iterate over the array.
  2. Check if the string contains each substring.
  3. If the condition is met, the string contains a substring from the array.
index.js
const str = 'hello world'; const arr = ['one', 'two', 'hello']; const contains = arr.some(element => { if (str.includes(element)) { return true; } return false; }); console.log(contains); // 👉️ true

The function we passed to the Array.some method gets called with each element in the array until it returns a truthy value or iterates over the entire array.

If the function returns true, the some() method short-circuits also returning true.

On each iteration, we check if the string contains the substring and return true if the condition is met.

The String.includes method returns true if the passed in substring is contained in the string.

Note that the includes() method is case sensitive. If you need to perform a case-insensitive check for whether a string contains a substring from an array, convert both strings to lowercase.

index.js
const str = 'HELlo world'; const arr = ['one', 'two', 'heLLO']; const contains = arr.some(element => { if (str.toLowerCase().includes(element.toLowerCase())) { return true; } return false; }); console.log(contains); // 👉️ true

We used the String.toLowerCase method to convert both strings to lowercase.

We could have also converted both strings to uppercase to achieve the same result. What's important is that both strings are of the same case for a case-insensitive comparison.

You can also use String.indexOf as an alternative to the includes() method.

index.js
const str = 'hello world'; const arr = ['one', 'two', 'hello']; const contains = arr.some(element => { if (str.indexOf(element) !== -1) { return true; } return false; }); console.log(contains); // 👉️ true

The String.indexOf method returns the index of the first occurrence of a substring in a string, or -1 if the substring is not contained in the string.

If the indexOf method doesn't return -1, the substring is contained in the string.

Which approach you pick is a personal preference. I'd go with using the includes() method as I find it more readable and direct.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.