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


当前回答

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

其他回答

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

全力支持;)

我也遇到过这样的问题。我有一个URL,我想检查链接是否以图像格式或其他文件格式结束,有一个图像格式数组。以下是我所做的:

const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
    
// false
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();

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