简体   繁体   English

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

[英]Check if a string contains any element of an array in 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);

The result is [ 'apple', 'kiwi', 'orange' ] .结果是[ 'apple', 'kiwi', 'orange' ] The 'apple' should get removed, but it isn't. 'apple'应该被删除,但事实并非如此。

Above code only filtered 'banana', not 'apple'.上面的代码只过滤了“香蕉”,而不是“苹果”。 I have many keywords to filter.我有很多关键字要过滤。 Is there an easier way?有没有更简单的方法?

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 checker uses 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来自MDM 上的Array.prototype.some()文档

The includes() method determines whether one string may be found within another string, returning true or false as appropriate. includes()方法确定是否可以在另一个字符串中找到一个字符串,并根据需要返回truefalse

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


As some latest ECMAScript features aren't supported in all browsers, you should use Babel to compile your code to ECMAScript 5.由于并非所有浏览器都支持某些最新的 ECMAScript 功能,因此您应该使用Babel将代码编译为 ECMAScript 5。

Problem lies in the for loop, which only iterates once since return ends the function, cutting off the for loop in the process.问题在于 for 循环,它只迭代一次,因为 return 结束了函数,在这个过程中切断了 for 循环。 So, you can update the code like so to make the function only return once the for loop has been completed .因此,您可以像这样更新代码,使函数仅在 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). 'every' 方法为数组中存在的每个元素执行一次提供的回调函数,直到找到一个回调函数返回假值(转换为布尔值时变为假的值)。 If such an element is found, the every method immediately returns false.如果找到这样的元素,every 方法会立即返回 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 )不会为已删除或从未分配值的索引调用它。( 取自此处

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

I think this can be greatly simplified.我认为这可以大大简化。 There is already a built in within javascript for checking these things. javascript 中已经内置了用于检查这些内容的功能。 Consider:考虑:

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

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

Check out this fiddle for 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>

对于寻找简单单线的人:

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

You can use some() function : to check if a string contains any element of an array.您可以使用some()函数:检查字符串是否包含数组的任何元素。

eg例如

var fruitsArr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
var myString = "I have an apple and a watermelon.";
var stringIncludesFruit = fruitsArr.some(fruit => myString.includes(fruit));

This function is pretty new.这个功能很新。 some() method accepts a callback where you define the condition you want to verify and it returns a boolean. some()方法接受一个回调,您可以在其中定义要验证的条件并返回一个布尔值。 Check the documentation at the link above.检查上面链接中的文档。

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, '\\$1');
};

var r = new RegExp(prohibited.map(escapeForRegex).join("|"));
arr.filter(function(v){ return !r.test(v) });
const stringInput = "I have a kiwi";
const arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
const exists = arr.some((t) => stringInput.indexOf(t) > -1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查一个数组是否包含另一个数组的任何元素,并且在JavaScript中为空 - Check if an array contains any element of another array with some null in JavaScript 检查嵌套数组是否包含JavaScript中另一个嵌套数组的任何元素 - Check if a nested array contains any element of another nested array in JavaScript 检查一个数组是否包含 JavaScript 中另一个数组的任何元素 - Check if an array contains any element of another array in JavaScript 检查字符串是否包含数组中忽略大小写的元素(JavaScript) - Check if string contains an element from array ignoring case (JavaScript) javascript-检查元素是否直接包含任何文本 - javascript - check if element directly contains any text javascript检查字符串是否包含任何符号 - javascript check if string contains any symbols 检查字符串是否包含任何字母(Javascript/jquery) - Check if string contains any letter (Javascript/jquery) 检查一个数组对象是否包含 JavaScript 中另一个数组的任何元素,然后根据打印 - Check if an array object contains any element of another array in JavaScript and then print according 检查字符串是否包含数组中存在的任何关键字 - Check if string contains any keywords that exists in array javascript检查元素是否包含某些字符串 - javascript check whether an element contains certain string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM