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!

3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.