检查字符串是否包含没有regExp的字符串数组中的任何一个 [英] Check if string contains any of array of strings without regExp

查看:44
本文介绍了检查字符串是否包含没有regExp的字符串数组中的任何一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.

任何人都可以分解我的代码为何无法正常工作吗?

Can anyone break my code down why it is not working properly?

     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;

谢谢您的时间!

推荐答案

您可以为此使用功能性方法.尝试Array.some.

You can use functional methods for this. Try 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)));

这篇关于检查字符串是否包含没有regExp的字符串数组中的任何一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆