首页 > 解决方案 > 检查字符串是否包含数组的任何元素

问题描述

假设我有一个字符串:

const subject = "This process is flawless"

我有一个数组:

const matchArray = ["process","procedure","job"]

我希望如果主题包含 matchArray 中的任何关键字,

if (subject matches any keyword of matchArray ){

console.log('true')
}

我的第一直觉是使用包含,但我不想将数组与字符串匹配,而是将字符串与数组匹配。

我仍在探索,如果有人可以指导我,那将非常有帮助。

编辑:我找到了这个灵魂,但有没有比这更好的解决方案

const subject = "This process is flawless"
const matchArray = ["process","procedure","job"]
const exists = matchArray.some(matchArray => subject.includes(matchArray))

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

标签: javascriptnode.js

解决方案


使用some()

const subject = "This process is flawless"
const matchArray = ["process", "procedure", "job"]

console.log(matchArray.some(i => subject.includes(i)))


推荐阅读