4

I noticed when trying to use OR operators inside an includes() function like this

x.includes("dogs"||"cats"||"birds"||"fish"||"frogs")

It will only trial the first string contained, and no further. I suspect that i'm either missing something obvious here or includes() isn't the right function to be used for this kind of situation.

The goal is to trial multiple strings to determine if they are substrings of x. Because i'm trying to use or operators, my intent is to not receive an array of boolean values for each trial string, but rather if any are true, then a single boolean value of true, otherwise false is desired.

srb633
  • 793
  • 3
  • 8
  • 16

4 Answers4

8

The || operator is not distributive. Function arguments are simply evaluated as expressions, so your call is equivalent to:

var temp = "dogs"||"cats"||"birds"||"fish"||"frogs";
x.includes(temp)

The value of a series of || operations is the first truthy value in the series. Since all non-empty strings are truthy, that's equivalent to:

var temp = "dogs";
x.includes(temp)

You need to use || on the result of calling includes for each string:

x.includes("dogs") || x.includes("cats") || x.includes("birds") ...

You can simplify this by using the some() method of arrays:

["dogs","cats","birds","fish","frogs"].some(species => x.includes(species))
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

includes only looks for one string. You can use .matchAll() function which returns an iterator of all matching results

const regex = /dogs|cats|birds|fish|frogs/g;
const str = 'the dogs, cats, fish and frogs all watched birds flying above them';
    
const exists = [...str.matchAll(regex)].length > 0;

console.log(exists);
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • 1
    I love that this method also allows for the direct output of what string was found without the `.length>0` – srb633 May 16 '20 at 06:56
  • Why would you matchAll? you only need to match once per the question. – niry May 16 '20 at 13:19
1

For this case, with a regular expression and a wanted boolean result RegExp#test comes in handy.

This approach does not return an iterator and need no array for getting a length of it.

const
    regex = /dogs|cats|birds|fish|frogs/g,
    str = 'the dogs, cats, fish and frogs all watched birds flying above them',
    exists = regex.test(str);

console.log(exists);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here's what I use in this situation:

let searchString = "fish"
console.log(["dogs","cats","birds","fish","frogs"].includes(searchString))
Baron Young
  • 181
  • 2
  • 13