Check if Array of Strings Contains a Substring in JavaScript
Table of Contents
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:
JAVASCRIPTconst array = ["hello", "world", "goodbye"];
const substring = "good";
Now we can use the find
method to check if the array contains the substring:
JAVASCRIPTconst array = ["hello", "world", "goodbye"];
const substring = "good";
const result = array.find(element => element.includes(substring));
console.log(result);
BASHgoodbye
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.
JAVASCRIPTconst 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!
- Getting Started with TypeScript
- Getting Started with Express
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React