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

时间:2017-10-25 06:32:49

标签: javascript arrays string

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

任何人都可以破解我的代码,为什么它无法正常工作?

     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;

感谢您的时间!

2 个答案:

答案 0 :(得分:3)

您可以使用功能方法。试试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 :(得分:0)

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