Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Bryan Garcia
To check if a string contains a substring from an array:
some()
method on the array, passing it a function.some
method returns true
if the condition is met at least once.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.
includes
method is not supported in Internet Explorer. If you have to support the browser, use the indexOf
method instead.// 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.
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.