How to Check If an Array of Strings Contains a Substring in JavaScript

Here are two ways to check if an array of strings contains a substring in JavaScript.

  1. Using includes() method and some() method
  2. Using includes() method and filter() method

Method 1: Using includes() method and some() method

The some() method is used to check whether at least one element in the array passes the test implemented by the provided function. In this case, we will use the includes() method within the some() method to check if any string in the array contains the given substring.

const arr = ["apple", "banana", "cherry", "date", "fig"];
const subStr = "an";

const hasSubstring = arr.some(word => word.includes(subStr));

console.log(hasSubstring);

Output

true

Method 2: Using includes() method and filter() method

The includes() method is used to check whether one string may be found within another string, returning true or false as appropriate. Combined with the filter() method, it creates a new array with all elements that pass the test implemented by the provided function.

const arr = ["apple", "banana", "cherry", "date", "fig"];
const subStr = "ry";

const result = arr.filter(word => word.includes(subStr));
console.log(result);

Output

[ 'cherry' ]

Conclusion

Use filter() and includes() when you want to get all the strings that contain a particular substring.

Use some() and includes() when you just want to know if any string in the array contains the substring.

Leave a Comment