检查字符串是否包含 JavaScript 中数组的任何元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37428338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:19:09  来源:igfitidea点击:

Check if a string contains any element of an array in JavaScript

javascriptarraysstring

提问by Juntae

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);

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

结果是[ 'apple', 'kiwi', 'orange' ]。本'apple'应该得到去除,但事实并非如此。

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

上面的代码只过滤了“香蕉”,而不是“苹果”。我有很多关键字要过滤。有更容易的方法吗?

采纳答案by Pranav C Balan

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 .

问题在于 for 循环,它只迭代一次,因为 return 结束了函数,在这个过程中切断了 for 循环。因此,您可以像这样更新代码,使函数仅在 for 循环完成后返回。

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);



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

为了减少您可以使用的功能every()indexOf()方法

The 'every' method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value (a value that becomes false when converted to a Boolean). If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.(Taken from here)

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

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);



For older browser check polyfill option of every method.

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



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

您甚至可以在这里使用正则表达式。使用数组生成正则表达式并用于test()检查匹配

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正则表达式吗?

回答by Micha? Per?akowski

It can be as simple as that:

可以这么简单:

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

const checker = value =>
  !['banana', 'apple'].some(element => value.includes(element));

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

ECMAScript 6 FTW!

ECMAScript 6 FTW!

The checkeruses an arrow function.

checker使用箭头功能

The !means that it will exclude all elements that doesn't meet the conditions.

!意味着它将排除所有不满足条件的元素。

The some()method tests whether some element in the array passes the test implemented by the provided function.

some()方法测试数组中的某个元素是否通过了提供的函数实现的测试。

from Array.prototype.some()docs on MDM

来自Array.prototype.some()MDM 上的文档

The includes()method determines whether one string may be found within another string, returning trueor falseas appropriate.

includes()方法确定是否可以在另一个字符串中找到一个字符串,返回truefalse视情况而定。

from String.prototype.includes()docs on MDM

来自String.prototype.includes()MDM 上的文档



As some latest ECMAScript features aren't supported in all browsers, you should use Babelto compile your code to ECMAScript 5.

由于并非所有浏览器都支持某些最新的 ECMAScript 功能,因此您应该使用Babel将代码编译为 ECMAScript 5。

回答by etchesketch

I think this can be greatly simplified. There is already a built in within javascript for checking these things. Consider:

我认为这可以大大简化。javascript 中已经内置了用于检查这些内容的功能。考虑:

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

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

  // indexOf() returns -1 if the element doesn't exist in the prohibited array
  return prohibited.indexOf( value ) == -1;
}

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

回答by blizzrdof77

Some may argue that this is a questionable practice, but you may find it useful to have a method that you can run on the string directly - in which case you could extend the JavaScript Stringobject using String.prototype.

有些人可能会争辩说这是一个有问题的做法,但您可能会发现拥有一个可以直接在字符串上运行的方法很有用 - 在这种情况下,您可以使用String.prototype扩展 JavaScript String对象。

Like this...

像这样...

String.prototype.containsAny = String.prototype.containsAny || function(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (this.indexOf(arr[i]) > -1) {
      return true;
    }
  }
  return false;
};

As you can see in this example, it will default to any existing definition of a containsAnymethod. Keep in mind: any time you're augmenting built-in objects, it's a good idea to at least check for the presence of the property first – perhaps some day it will exist... ˉ\_(ツ)_/ˉ

正如您在此示例中看到的,它将默认为任何现有的containsAny方法定义。记住:任何时候你增加内置对象时,最好至少先检查属性是否存在——也许有一天它会存在...... ˉ\_(ツ)_/ˉ

Check out this fiddlefor usage or see below:

查看这个小提琴的用法或见下文

var str = 'This is a sentence as a string.';

console.log(str.containsAny(['string1', 'string2', 'string3'])); // -> returns false
console.log(str.containsAny(['string', 'string1', 'string2'])); // -> returns true
<script src="//cdn.simpledigital.net/common/js/extensions/String.prototypeHelpers.js"></script>

回答by Lahori

For someone looking for simple, single-liner:

对于寻找简单单线的人:

arr.filter(item => !prohibited.some(prohb => item.includes(prohb)))  // ["kiwi", "orange"]

回答by Thomas

For example by building a RegExp and testing against that:

例如,通过构建一个 RegExp 并对其进行测试:

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

var escapeForRegex = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\])/g, '\');
};

var r = new RegExp(prohibited.map(escapeForRegex).join("|"));
arr.filter(function(v){ return !r.test(v) });