Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "OR" operator inside includes() to trial the existence of any substrings within a string?

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.

like image 626
srb633 Avatar asked Oct 23 '25 19:10

srb633


1 Answers

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))
like image 174
Barmar Avatar answered Oct 26 '25 10:10

Barmar