非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。
当前回答
全面支持(除了@ricca的版本)。
wordsArray = ['hello', 'to', 'nice', 'day'] yourString = '你好。今天天气不错’。 result = wordsArray。每个(w => yourstring .include (w)) console.log(“结果:”,结果)
其他回答
如果数组不大,可以使用indexOf()循环并逐个检查每个子字符串。或者,您可以构造一个带有子字符串作为替代的正则表达式,这可能更有效,也可能不更有效。
使用underscore.js或lodash.js,你可以对字符串数组执行以下操作:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
在一个字符串上:
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';
使用滤镜:
obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))
以下是目前为止(在我看来)最好的解决方案。这是一个现代的(ES6)解决方案,它:
是高效的(一行!) 避免for循环 与其他答案中使用的some()函数不同,这个函数不仅返回一个布尔值(true/false) 相反,它要么返回子字符串(如果它在数组中找到),要么返回undefined 更进一步,允许您选择是否需要部分子字符串匹配(示例如下)
享受吧!
const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));
在这里,found将被设置为'abc'。这将适用于精确的字符串匹配。
如果你用:
const found = arrayOfStrings.find(v => str.includes(v));
同样,found在本例中被设置为'abc'。这不允许部分匹配,所以如果str被设置为'ab', found将是未定义的。
And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));
代替。如果str被设为'ab' found就会被设为'abc'
容易peasy !
const str = '此字符串是否包含下面数组中的一个或多个字符串?'; Const arr = ['one', 'two', 'three']; Const包含= arr。Some (element => { If (str.includes(element)) { 返回true; } 返回错误; }); console.log(包含);/ /正确的