很简单。在JavaScript中,我需要检查一个字符串是否包含数组中包含的任何子字符串。
很简单。在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的some数组方法和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
}
最佳答案在这里:这也是不区分大小写的。
var specsFilter = [.....];
var yourString = "......";
//if found a match
if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
// do something
}
Array.prototype.check = function (s) {
return this.some((v) => {
return s.indexOf(v) >= 0;
});
};
在T.J Crowder的回答基础上进行改进
使用转义的正则表达式来测试至少出现一次的子字符串中的至少一个。
function buildSearch(substrings) {
return new RegExp(
substrings
.map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
.join('{1,}|') + '{1,}'
);
}
var pattern = buildSearch(['hello','world']);
console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));
我并不建议您去扩展/修改String
的原型,但这是我所做的:
String.prototype.includes = function (includes) {
console.warn("String.prototype.includes() has been modified.");
return function (searchString, position) {
if (searchString instanceof Array) {
for (var i = 0; i < searchString.length; i++) {
if (includes.call(this, searchString[i], position)) {
return true;
}
}
return false;
} else {
return includes.call(this, searchString, position);
}
}
}(String.prototype.includes);
console.log('"Hello, World!".includes("foo");', "Hello, World!".includes("foo") ); // false
console.log('"Hello, World!".includes(",");', "Hello, World!".includes(",") ); // true
console.log('"Hello, World!".includes(["foo", ","])', "Hello, World!".includes(["foo", ","]) ); // true
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
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
const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
// false
map()
函数吗?我记得曾经读过相关的内容... - Martin Hennings