Check if Array of Strings Contains a Substring in JavaScript

Updated onbyAlan Morel
Check if Array of Strings Contains a Substring in JavaScript

When you have an array of strings, sometimes you want to check if part of a string exists in any of the elements in that array.

In this case, you'll need to search the entire array to see if the substring is found in any of the elements.

In this post, we'll learn how to check an array of strings to see if it contains a substring in JavaScript.

How to check if an array of strings contains a substring

In order to check if an array of strings contains a substring, we can use the built-in find method.

This method will call a callback function for each element in the array and return the value of the first element in the array that returns true from the callback function.

We just need to pass in a callback function that checks if the element contains our substring.

Let's start with our array and substring:

JAVASCRIPT
const array = ["hello", "world", "goodbye"]; const substring = "good";

Now we can use the find method to check if the array contains the substring:

JAVASCRIPT
const array = ["hello", "world", "goodbye"]; const substring = "good"; const result = array.find(element => element.includes(substring)); console.log(result);
BASH
goodbye

Because the last element was the only one that returned true from the callback function, we get the value of that element.

Another way to accomplish this is to use the filter method.

You can pass it the same callback function that you used with find and it will return an array of elements that returned true from the callback function.

JAVASCRIPT
const array = ["hello", "world", "goodbye"]; const substring = "good"; const result = array.filter(element => element.includes(substring)); console.log(result);
BASH
['goodbye']

The benefit of using filter is that you get back all elements that passed the callback function instead of just the first.

Conclusion

In this post, we learned how to check an array of strings for elements that contain a specific substring.

Simply use the find or filter methods and pass it a callback function that checks if the value contains the specific substring.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.