非常直截了当。在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
}
我也遇到过这样的问题。我有一个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
var str = "A for apple" var subString = ["apple"] console.log (str.includes (subString))
这太迟了,但我刚刚遇到了一个问题。在我自己的项目中,我使用以下方法来检查字符串是否在数组中:
["a","b"].includes('a') // true
["a","b"].includes('b') // true
["a","b"].includes('c') // false
通过这种方式,你可以获取一个预定义数组并检查它是否包含字符串:
var parameters = ['a','b']
parameters.includes('a') // 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
}
}