非常直截了当。在javascript中,我需要检查字符串是否包含数组中持有的任何子字符串。


当前回答

使用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

其他回答

Javascript函数使用搜索字符串或搜索字符串数组搜索标签或关键字数组。(使用ES5的一些数组方法和ES6的箭头函数)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

使用示例:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

单线解决方案

substringsArray.some(substring=>yourBigString.includes(substring))

如果子字符串存在\不存在,则返回true\false

需要ES6支持

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}

我并不是建议你去扩展/修改String的原型,但这是我所做的:

String.prototype.includes ()

String.prototype.includes = function (includes) { console.warn("String.prototype.includes() has been modified."); return function (searchString, position) { if (searchString instanceof Array) { for (var i = 0; i < searchString.length; i++) { if (includes.call(this, searchString[i], position)) { return true; } } return false; } else { return includes.call(this, searchString, position); } } }(String.prototype.includes); console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false

没有内置的东西可以帮你做这个,你必须为它写一个函数,尽管它可以只是一个对某些数组方法的回调。

有两种方法:

数组一些方法 正则表达式

数组的一些

数组some方法(在ES5中添加)使这非常简单:

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
    // There's at least one
}

更好的箭头函数和newish includes方法(都是ES2015+):

if (substrings.some(v => str.includes(v))) {
    // There's at least one
}

生活例子:

const substrings = ["one", "two", "three"]; let str; // Setup console.log(`Substrings: ${substrings}`); // Try it where we expect a match str = "this has one"; if (substrings.some(v => str.includes(v))) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); } // Try it where we DON'T expect a match str = "this doesn't have any"; if (substrings.some(v => str.includes(v))) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); }

正则表达式

如果你知道字符串不包含任何正则表达式中的特殊字符,那么你可以欺骗一下,像这样:

if (new RegExp(substrings.join("|")).test(string)) {
    // At least one match
}

...这将创建一个正则表达式,它是您正在寻找的子字符串的一系列更改(例如,one|two),并测试是否有匹配它们中的任何一个,但如果任何子字符串包含正则表达式中的任何特殊字符(*,[等),您必须首先转义它们,您最好只做无聊的循环。有关如何逃离它们的信息,请参阅这个问题的答案。

生活例子:

const substrings = ["one", "two", "three"]; let str; // Setup console.log(`Substrings: ${substrings}`); // Try it where we expect a match str = "this has one"; if (new RegExp(substrings.join("|")).test(str)) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); } // Try it where we DON'T expect a match str = "this doesn't have any"; if (new RegExp(substrings.join("|")).test(str)) { console.log(`Match using "${str}"`); } else { console.log(`No match using "${str}"`); }