1

What I am trying to accomplish (Pseudocode):

if caption.includes("dog" or "fish" or "bird" or "cat") { 
  // notify me 
}

caption is a dynamic variable. I'm able to get it to work using one keyword but I'm trying to have it check against a list of words. Doesn't need to be with includes(), whatever works.

Thank you for your time!

adiga
  • 34,372
  • 9
  • 61
  • 83
Hugo
  • 25
  • 6
  • Please, post the code you've tried. – aaaaane Feb 27 '19 at 07:33
  • 1
    Possible duplicate of [Check if an array contains any element of another array in JavaScript](https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript) – VLAZ Feb 27 '19 at 07:43
  • 1
    Actually, probably more on topic [here is one for string](https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript), although you can do the same as arrays using `arr.some(item => str.includes(item))` – VLAZ Feb 27 '19 at 07:45

2 Answers2

3

You can create an array of keywords and use some to check if at least one of them exists in the string like this:

const caption = "I love dogs";
const animals = ["dog", "fish", "bird", "cat"];
const exists = animals.some(animal => caption.includes(animal))

if (exists) {
  console.log("Yes");
  // notify 
}

Or you can use a regex like this:

const animals = ["dog", "fish", "bird", "cat"];
const regex = new RegExp(animals.join("|")) // animals seperated by a pipe "|"

if (regex.test("I love cats")) {
  console.log("Yes");
}

// if you don't want to create an array then:
if (/dog|fish|bird|cat/.test("I love elephants")) {
  console.log("Yes");
} else {
  console.log("No")
}
adiga
  • 34,372
  • 9
  • 61
  • 83
1

Don't need to create an extra array, use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search

let caption = 'cat'
if(caption.search(/dog|fish|cat|bird/) !== -1) {
 console.log('found')
}
AZ_
  • 3,094
  • 1
  • 9
  • 19