2

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

0

4 Answers 4

3

You could use the some method:

if (["apple", "pear", "orange"].some(x => fruit.includes(x))) {
    // Do something...
Sign up to request clarification or add additional context in comments.

Comments

1

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');
}

2 Comments

@KoshVery if so then maybe i need a \s+ in a regex. Beside, 'spearmint'.includes('pear') return true also.
You're getting closer =)) Try /\b(apple|pear|orange)\b/.
1

.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));

Comments

0

you can use forEach loop

const fruit = ['apple', 'orange'];

fruit.forEach( function(v, i) {
    if ( fruit[i].includes('orange') ) {
    // do you stuff
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.