Using The Includes Method On A String With Multiple Values
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 no
Solution 1:
You could use the some
method:
if (["apple", "pear", "orange"].some(x => fruit.includes(x))) {
// Do something...
Solution 2:
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');
}
Solution 3:
.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'];
constmatches = (array1, array2) => array1.filter(word => array2.includes(word));
console.log(matches(primary, search));
Solution 4:
you can use forEach
loop
const fruit = ['apple', 'orange'];
fruit.forEach( function(v, i) {
if ( fruit[i].includes('orange') ) {
// do you stuff
}
});
Post a Comment for "Using The Includes Method On A String With Multiple Values"