Reputation: 21
I want to check if a string has any of the following words, apple, pear, orange and if it does, do some code. However my code only currently checks for the first word, apple and not the other 2. Fruit variable gets sent from a client side.
var fruit = fruit;
if (fruit.includes(["apple", "pear", "orange"])
{
//do some code
}
I tried | instead of a comma
I need it so it checks all for all of the words, not just the first
Upvotes: 2
Views: 1631
Reputation: 43910
.includes()
returns a Boolean (true/false) and it appears that you want the actual matches to return instead. .find()
returns the match but like .include()
it stops after the first match so you'll need to iterate through the search keys.
The following demo runs .filter()
through the array to be searched (primary
). .filter()
will return the current value that's evaluated as true. By running .includes()
on the search array (search
) inside the .filter()
you can search each element of array primary
.
const primary = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'];
const search = ['beta', 'delta', 'omega'];
const matches = (array1, array2) => array1.filter(word => array2.includes(word));
console.log(matches(primary, search));
Upvotes: 1
Reputation: 11975
You can use regex instead of includes()
with a loop to solve it.
Demo:
var fruit = "green dpear";
if (/\b(apple|pear|orange)\b/.test(fruit)) {
console.log('match');
} else {
console.log('not_match');
}
Upvotes: 1
Reputation: 968
you can use forEach
loop
const fruit = ['apple', 'orange'];
fruit.forEach( function(v, i) {
if ( fruit[i].includes('orange') ) {
// do you stuff
}
});
Upvotes: 0
Reputation: 311393
You could use the some
method:
if (["apple", "pear", "orange"].some(x => fruit.includes(x))) {
// Do something...
Upvotes: 3