Languages
[Edit]
EN

JavaScript - check if string contains text from array of substrings

0 points
Created by:
Frida-Timms
667

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.

 

References

  1. Array.prototype.some() - JavaScript | MDN
  2. String.prototype.includes() - JavaScript | MDN
  3. String.prototype.indexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - check if string contains word from array of substrings
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join