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:
const array = ["hello", "world", "goodbye"];
const substring = "good";
Now we can use the find
method to check if the array contains the substring:
const array = ["hello", "world", "goodbye"];
const substring = "good";
const result = array.find(element => element.includes(substring));
console.log(result);
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.
const array = ["hello", "world", "goodbye"];
const substring = "good";
const result = array.filter(element => element.includes(substring));
console.log(result);
['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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!