【问题标题】:Check if string contains any of array of strings without regExp [duplicate]检查字符串是否包含任何没有regExp的字符串数组[重复]
【发布时间】:2018-04-06 03:07:30
【问题描述】:

我正在检查字符串输入是否包含任何字符串数组。它通过了大部分测试,但没有通过以下测试。

谁能分解我的代码为什么它不能正常工作?

     function checkInput(input, words) {
      var arr = input.toLowerCase().split(" ");
      var i, j;
      var matches = 0;
      for(i = 0; i < arr.length; i++) {
        for(j = 0; j < words.length; j++) {
          if(arr[i] == words[j]) {
            matches++;
          }
        }
      }
      if(matches > 0) {
        return true;
      } else {
        return false;
      }
    };

checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.', 
    ["matter", "definitely"])); // returns false; should be returning true;

感谢您的宝贵时间!

【问题讨论】:

  • 不是案例问题
  • 你为什么不用正则表达式?
  • 很多非正则表达式的简单方法可以做到这一点。 if (words.some(word =&gt; input.includes(word))) {/*do a thing*/} 在第一场比赛后停止。

标签: javascript arrays string


【解决方案1】:

您可以为此使用函数式方法。试试 Array.some。

const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));

【讨论】:

  • 这是区分大小写的。 OP 想要一个不区分大小写的解决方案。
  • 不区分大小写与问题无关。非常非常清楚的是,您要对字符串进行小写。不鼓励吸食。
  • 问题实际上是“如何查看一个字符串是否包含任何字符串数组”,它是一个普通的鞋面Q之上的明显重复。它将被关闭,我的答案将是走了。我只是想让 OP 看到有更好的方法哈哈
  • 你是对的!顺便说一句,你的答案是一个很好的答案。 +1
【解决方案2】:

您可以使用array#includes 检查输入中是否存在单词,并将inputwords 转换为小写,然后使用array#includes

function checkInput(input, words) {
 return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}

console.log(checkInput('"Definitely," he said in a matter-of-fact tone.', 
["matter", "definitely"]));

您可以创建regular expression 并使用i 标志来指定不区分大小写

function checkInput(input, words) {
 return words.some(word => new RegExp(word, "i").test(input));
}

console.log(checkInput('"Definitely," he said in a matter-of-fact tone.', 
["matter", "definitely"]));

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 2015-09-14
    • 2020-12-01
    • 2021-05-02
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多