检查字符串是否包含任何一个字符串数组中的字符串,不使用正则表达式

5

我正在检查一个字符串输入是否包含任何字符串数组中的任何一个。它通过了大多数测试,但以下测试未通过。

有人能解释一下为什么我的代码不能正常工作吗?

     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;

感谢您抽出时间来阅读本文!

1
its not a case issue - omarjmh
为什么你不使用正则表达式? - inetphantom
{btsdaf} - user1596138
2个回答

13
你可以使用函数式方法来实现。尝试使用 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)));

1
{btsdaf} - frogatto
{btsdaf} - user1596138
问题实际上是“如何查看字符串是否包含字符串数组中的任何一个”,这是一个明显的重复问题,而且还是一个普遍的吸血鬼问题。它将被关闭,我的答案也将消失。我只是想让OP看到有更好的方法哈哈。 - user1596138

6
你可以使用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"]));

您可以创建正则表达式并使用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"]));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接