检查字符串是否包含JavaScript中数组的任何元素 [英] Check if a string contains any element of an array in JavaScript

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

问题描述

如何检查字符串是否包含数组的任何元素?我想过滤一些数组,如果元素有一些字符串.请参见下面的代码.

How can I check if a string contains any element of an array? I want to filter some array if the element has some string. Please see below code.

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];

function checker(value) {
  var prohibited = ['banana', 'apple'];

  for (var i = 0; i < prohibited.length; i++) {
    if (value.indexOf(prohibited[i]) == -1) {
      return true;
    } else {
      return false;
    }
  }
}

arr = arr.filter(checker);
console.log(arr);

结果为[ 'apple', 'kiwi', 'orange' ]. 'apple'应该被删除,但不是.

The result is [ 'apple', 'kiwi', 'orange' ]. The 'apple' should get removed, but it isn't.

以上代码仅过滤了香蕉",而不过滤了苹果".我有很多关键字要过滤.有没有更简单的方法?

Above code only filtered 'banana', not 'apple'. I have many keywords to filter. Is there an easier way?

推荐答案

问题位于for循环中,由于return结束了该函数,因此该循环仅迭代一次,从而中断了过程中的for循环.因此,您可以像这样更新代码,以使该函数仅在for循环完成后才返回.

Problem lies in the for loop, which only iterates once since return ends the function, cutting off the for loop in the process. So, you can update the code like so to make the function only return once the for loop has been completed .

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];

function checker(value) {
  var prohibited = ['banana', 'apple'];

  for (var i = 0; i < prohibited.length; i++) {
    if (value.indexOf(prohibited[i]) > -1) {
      return false;
    }
  }
  return true;
}

arr = arr.filter(checker);
console.log(arr);

为简化功能,可以使用 indexOf() 方法

For reducing the function you can use every() and indexOf() methods

'every'方法对数组中存在的每个元素执行一次提供的回调函数,直到找到其中回调返回虚假值(当该值转换为布尔值时为false的值)的回调函数.如果找到了这样的元素,则every方法将立即返回false.否则,如果callback对所有元素都返回了true值,则每个元素都将返回true.仅对具有分配值的数组索引调用回调;对于已删除或从未分配值的索引不会调用它.(

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];

function checker(value) {
  var prohibited = ['banana', 'apple'];
  return prohibited.every(function(v) {
    return value.indexOf(v) == -1;
  });
}

arr = arr.filter(checker);
console.log(arr);

对于较旧的浏览器检查polyfill选项每种方法的.

您甚至可以在此处使用正则表达式.使用数组生成正则表达式,并使用 test() 检查匹配情况

You could even use a regex here. Generate regex using the array and use test() to check match

var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];

function checker(value) {
  var prohibited = ['banana', 'apple'];
  var regex = new RegExp(prohibited.map(function(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
  }).join('|'));
  return !regex.test(value);
}

arr = arr.filter(checker);
console.log(arr);

请参考此答案以获取字符串到正则表达式的转换:

Refer this answer for string to regex conversion : Can you create JavaScript regexes on the fly using string variables?

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

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