【问题标题】:Know if a word of a string is in an array Node JS知道一个字符串的一个单词是否在数组中 Node JS
【发布时间】:2023-03-04 19:27:02
【问题描述】:

我有一个字符串var input = "Hello there, my name is Felix" 和一个数组var names = ["John", "Bob", "Felix", "Alicia"]。我如何知道 input 是否包含 names 的一个或多个单词? 谢谢。 编辑:我想知道inputnames 中是什么词

【问题讨论】:

标签: javascript arrays node.js string


【解决方案1】:

使用 Array#filter 和 String#includes 将获取输入中包含的所有名称。

const input = "Hello there, my name is Felix"
const names = ["John", "Bob", "Felix", "Alicia"]

const res = names.filter(n=>input.includes(n));

console.log(res);

【讨论】:

    【解决方案2】:

    这里有很多选项,我认为最简洁的选项如下:

    const namesInString = names.filter( name => input.contains(name) ) 在这种方法中,filter 遍历数组并将任何给定的名称存储在生成的 namesInString 数组中(如果在数组中找到该名称)。

    在不相关的注释中,请注意区分大小写,因此完整的解决方案应该是: const namesInString = names.filter( name => input.toLowerCase().contains(name.toLowerCase()) )

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      另一种选择是使用filter()match(),在每次迭代时创建一个新的Regular Expression,并在需要时设置标志ignoreCase

      const input = "Hello there, my name is Felix";
      const names = ["John", "Bob", "Felix", "Alicia", "hello"];
      
      let res = names.filter(name => input.match(RegExp(name, "i")));
      console.log("With ignore-case enabled: ", res);
      
      res = names.filter(name => input.match(RegExp(name)));
      console.log("Without ignore-case enabled: ", res);

      但是,如果您不介意获取匹配项并且只需要测试数组中的某些字符串是否出现在输入字符串上,您可以使用some() 使用更快的方法。

      const input1 = "Hello there, my name is Felix";
      const input2 = "I don't have matches";
      const names = ["John", "Bob", "Felix", "Alicia", "hello"];
      
      const res1 = names.some(name => input1.match(RegExp(name, "i")));
      console.log("Has coincidences on input1? ", res1);
      
      const res2 = names.some(name => input2.match(RegExp(name, "i")));
      console.log("Has coincidences on input2? ", res2);

      【讨论】:

        猜你喜欢
        • 2017-07-08
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        • 2022-01-11
        相关资源
        最近更新 更多