关于javascript:检查字符串是否包含任何没有regExp的字符串数组

Check if string contains any of array of strings without regExp

本问题已经有最佳答案,请猛点这里访问。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
     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
2
3
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));


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

1
2
3
4
5
6
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标志指定大小写不敏感

1
2
3
4
5
6
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"]));