Check if String contains Substring from Array in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Bryan Garcia

Check if String contains Substring from an Array #

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

  1. Call the some() method on the array, passing it a function.
  2. On each iteration, check if the string contains the current array element.
  3. The some method returns true if the condition is met at least once.
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 pass 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 and also returns true.

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

The includes method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.
index.js
// Supported in IE 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, we know that the substring is contained in the string.

This approach is not as direct and intuitive as using the includes method, however if you have to support Internet Explorer, it gets the job done.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee