JavaScript - check if string contains text from array of substrings
In this article, we would like to show you how to check if string contains text from array of substrings using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var text = 'Hello world!';
var array = ['word1', 'word2', 'Hello'];
var result = array.some(function(value) {
return text.indexOf(value) >= 0;
});
console.log(result); // true
or:
// ONLINE-RUNNER:browser;
var text = 'Hello world!';
var array = ['word1', 'word2', 'Hello'];
var result = array.some(function(value) {
return text.includes(value);
});
console.log(result); // true
Practical examples
In this section, we present reusable arrow functions which you can use to check if the string contains text from an array of substrings.
Both of the examples below use Array
some()
method that tests whether at least one element in the array passes the test implemented by the provided function.
1. using indexOf()
In this example, we use indexOf()
method to check if any element from the array has an index >=0
inside the string.
// ONLINE-RUNNER:browser;
const containsText = (text, array) => {
const result = array.some((value) => {
return text.indexOf(value) >= 0;
});
return result;
};
// Usage example:
console.log(containsText('Hello world!', ['word1', 'Hello'])); // true
console.log(containsText('Example text', ['word1', 'word2'])); // false
Note:
indexOf()
method returns-1
if the element is not present in the string.
2. using includes()
In this example, we use includes()
method to check if there's any element from the array inside the given string.
// ONLINE-RUNNER:browser;
const containsText = (text, array) => {
const result = array.some((value) => text.includes(value));
return result;
};
console.log(containsText('Hello world!', ['word1', 'Hello'])); // true
console.log(containsText('Example text', ['word1', 'word2'])); // false
Note:
includes()
method performs a case-sensitive search.