【问题标题】:Check if a string contains any element of array [duplicate]检查字符串是否包含数组的任何元素[重复]
【发布时间】:2021-05-02 00:03:54
【问题描述】:

假设我有一个字符串:

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 
}

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    如果您想分别检查数组的每个索引是否存在,这是我的代码

    const subject = "This process is flawless"
    const matchArray = ["process","procedure","job"]
    const subject_array=subject.split(" ");
    console.log(subject_array);// split the string by space
    // loop on matchArray matchArray
    for(i=0;i<matchArray.length;i++){
    const c_string=matchArray[i];
    var check = subject.includes(c_string);
    if(check==true){
     console.log(c_string,' is present');
        }
      }
    

    Here is the out put

    【讨论】:

      【解决方案2】:

      使用some()

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-27
        • 2016-09-22
        • 1970-01-01
        • 2011-12-23
        • 2019-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多