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