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


当前回答

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

其他回答

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

确切的答案应该是。

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

如果数组不大,可以使用indexOf()循环并逐个检查每个子字符串。或者,您可以构造一个带有子字符串作为替代的正则表达式,这可能更有效,也可能不更有效。

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

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

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

var parameters = ['a','b']
parameters.includes('a')    // true

使用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
convert_to_array = function (sentence) {
     return sentence.trim().split(" ");
};

let ages = convert_to_array ("I'm a programmer in javascript writing script");

function confirmEnding(string) {
let target = "ipt";
    return  (string.substr(-target.length) === target) ? true : false;
}

function mySearchResult() {
return ages.filter(confirmEnding);
}

mySearchResult();

您可以像这样检查并使用过滤器返回匹配单词的数组