Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

When working with strings in JavaScript, you may want to check if a given string contains all values from a list of candidates.

JavaScript comes with a String#includes(needle) determining whether the string contains the given needle. You can combine the existing method with array methods to check whether all candidate strings are part of the base string.

Node.js Series Overview

Check If a String Includes All Strings

JavaScript comes with helpful array and string methods that will help you determine whether a base string contains all values from a list of strings. You can use the Array#every in combination with the String#includes method to check if all items from the candidate list are part of the base string:

/**
 * Determine whether the given `str` includes all needles.
 *
 * @returns {Boolean}
 */ 
includesAll(str, ...needles) {  
  return [].concat(...needles).every(needle => {
    return str.includes(needle)
  })
}

const includesAll = includesAll('Hello Marcus, you look good today!', ['look', 'good'])  
// true

const includesAll = includesAll('Hello Marcus, you look good today!', ['look', 'bad'])  
// false

The includesAll method returns true if all items in the candidate list are part of the source string. Otherwise, it returns false.

Use the @supercharge/strings Package

I’m the maintainer of the @supercharge/strings package providing convenient string utilities. Checking if a string contains all needles is one of the available methods:

const Str = require('@supercharge/strings')

const includesAll = Str('Hello Marcus, you look good today!').includesAll('look', 'good')  
// true

const includesAll = Str('Hello Marcus, you look good today!').includesAll('look', 'bad')  
// false

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.