[英]Javascript: Check for an array of keywords match in a string
我想要完成的任務(偽代碼):
if caption.includes("dog" or "fish" or "bird" or "cat") {
// notify me
}
caption
是一個動態變量。 我能夠使用一個關鍵字讓它工作,但我試圖檢查一個單詞列表。 不需要使用includes(),無論什么工作。
感謝您的時間!
您可以創建一個關鍵字數組,並使用some
來檢查字符串中是否至少存在一個關鍵字,如下所示:
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 }
或者您可以使用這樣的正則表達式:
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") }
不需要創建額外的數組,請使用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') }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.