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


当前回答

substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

全力支持;)

其他回答

单线解决方案

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

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

需要ES6支持

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.every(substring=>yourBigString.indexOf(substring) === -1)

全力支持;)

var str = "A for apple" var subString = ["apple"] console.log (str.includes (subString))

基于t。j。克劳德的答案

使用转义的RegExp测试至少一个子字符串的“至少一次”出现。

函数buildSearch(substrings) { 返回新的RegExp( 子字符串 . map(函数(s) {s.replace返回 (/[.*+?^${}()|[\]\\]/ g , '\\$&');}) .join('{1,}|') + '{1,}' ); } var pattern = buildSearch(['hello','world']); console.log(模式。测试('你好')); console.log(模式。Test ('what a wonderful world')); console.log(模式。Test ('my name is…'));