Javascript Check if an Array of Strings contains a Substring Example; In this tutorial you will learn how to check if a JavaScript array contains a substring in JS.
Check if Array contains a Substring with Array.filter
To check if an array includes an object in JavaScript we can use Array.filter. The Array.find method returns an array with all the elements that satisfy the condition.
// Supported in IE 9-11
const array = ['coding', 'driver'];
const substring = 'codi';
const matched = array.filter(element => {
if (element.indexOf(substring) !== -1) {
return true;
}
});
console.log(matched ); // [ 'coding' ]
if (matched .length > 0) {
// array contains substring match
}
Check if Array contains a Substring with Array.find
To check if an array includes an object in JavaScript we can use Array.find. The Array.find method will return the object if the conditional check is satisfied at least once otherwise return undefined.
// Not Supported in IE 6-11
const array = ['coding', 'driver'];
const substring = 'codi';
const matched = array.find(element => {
if (element.includes(substring)) {
return true;
}
});
console.log(matched); // coding
if (matched!== undefined) {
// array contains substring match
}
The Array.find method gets invoked with each element of the array until it returns a truthy value or exhausts the array’s elements.