How to check if a string contains text from an arr

2019-01-06 09:15发布

Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.

13条回答
男人必须洒脱
2楼-- · 2019-01-06 09:44

One line solution

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

Returns true\false if substring exists\does'nt exist

Needs ES6 support

查看更多
Ridiculous、
3楼-- · 2019-01-06 09:49

Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)

// 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;
}

Example usage:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}
查看更多
等我变得足够好
4楼-- · 2019-01-06 09:49

This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:

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

This way you can take a predefined array and check if it contains a string:

var parameters = ['a','b']
parameters.includes('a')    // true
查看更多
叼着烟拽天下
5楼-- · 2019-01-06 09:51

Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};
查看更多
地球回转人心会变
6楼-- · 2019-01-06 09:52
var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

edit: If the order of the tests doesn't matter, you could use this (with only one loop variable):

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}
查看更多
疯言疯语
7楼-- · 2019-01-06 09:52

If the array is not large, you could just loop and check the string against each substring individually using indexOf(). Alternatively you could construct a regular expression with substrings as alternatives, which may or may not be more efficient.

查看更多
登录 后发表回答