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


当前回答

这太迟了,但我刚刚遇到了一个问题。在我自己的项目中,我使用以下方法来检查字符串是否在数组中:

["a","b"].includes('a')     // true
["a","b"].includes('b')     // true
["a","b"].includes('c')     // false

通过这种方式,你可以获取一个预定义数组并检查它是否包含字符串:

var parameters = ['a','b']
parameters.includes('a')    // 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
}

对于用谷歌搜索的人来说,

确切的答案应该是。

const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
   // Will only return when the `str` is included in the `substrings`
}

const str = '此字符串是否包含下面数组中的一个或多个字符串?'; Const arr = ['one', 'two', 'three']; Const包含= arr。Some (element => { If (str.includes(element)) { 返回true; } 返回错误; }); console.log(包含);/ /正确的

最好的答案是: 这也是不区分大小写的

    var specsFilter = [.....];
    var yourString = "......";

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }

如果您正在处理一长串子字符串,这些子字符串由空格或任何其他常见字符分隔的完整“单词”组成,那么您可以在搜索中使用一些聪明的方法。

首先把你的字符串分成X组,然后X+1,然后X+2,…X和Y应分别为子字符串中单词最少和最多的单词数。例如,如果X是1,Y是4,“Alpha Beta Gamma Delta”变成:

"阿尔法" "贝塔" "伽马" "德尔塔"

"阿尔法·贝塔" "贝塔·伽马" "伽马·德尔塔"

"Alpha Beta Gamma" "Beta Gamma Delta"

"Alpha Beta Gamma Delta"

如果X是2 Y是3,那么你可以省略第一行和最后一行。

现在,如果您将它插入到Set(或Map)中,就可以快速搜索这个列表,比字符串比较快得多。

缺点是你不能搜索像“ta Gamm”这样的子字符串。当然,你可以通过按字符而不是按单词进行分割来实现这一点,但这样你通常需要构建一个庞大的Set,并且这样做所花费的时间/内存超过了好处。