Ad

Javascript: Check For An Array Of Keywords Match In A String

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!

Ad

Answer

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")
}

Ad
source: stackoverflow.com
Ad