Hugo
Hugo

Reputation: 25

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!

Upvotes: 1

Views: 2579

Answers (2)

adiga
adiga

Reputation: 35222

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

Upvotes: 3

arizafar
arizafar

Reputation: 3122

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

Upvotes: 1

Related Questions