给定一个字符串数组:
x = ["banana","apple","orange"]
是否有用于执行通配符搜索的内置快捷方式?
即,也许
x.indexOf("*na*") //returns index of a string containing the substring na
给定一个字符串数组:
x = ["banana","apple","orange"]
是否有用于执行通配符搜索的内置快捷方式?
即,也许
x.indexOf("*na*") //returns index of a string containing the substring na
扩展 Pim 的答案,正确的方法(没有 jQuery)是这样的:
Array.prototype.find = function(match) {
return this.filter(function(item){
return typeof item == 'string' && item.indexOf(match) > -1;
});
}
但实际上,除非您在多个地方使用此功能,否则您可以使用现有filter
方法:
var result = x.filter(function(item){
return typeof item == 'string' && item.indexOf("na") > -1;
});
RegExp 版本类似,但我认为它会产生更多开销:
Array.prototype.findReg = function(match) {
var reg = new RegExp(match);
return this.filter(function(item){
return typeof item == 'string' && item.match(reg);
});
}
不过,它确实提供了允许您指定有效 RegExp 字符串的灵活性。
x.findReg('a'); // returns all three
x.findReg("a$"); // returns only "banana" since it's looking for 'a' at the end of the string.
扩展 @Shmiddty 的答案,这里有一些有用的 JavaScript 想法:
Array.prototype.method = function(arg) { return result; }
Array.filter(function(e) { return true|false; })
Array.map(function(e) { return formula(e); })
/.*na.*/
或new Regex('.*na.*')
let result = regex.test(input);
即我更喜欢输入参数是一个正则表达式,所以,它给你:
解决方案 1:过滤、测试、映射和 indexOf
Array.prototype.find = function(regex) {
const arr = this;
const matches = arr.filter( function(e) { return regex.test(e); } );
return matches.map(function(e) { return arr.indexOf(e); } );
};
let x = [ "banana", "apple", "orange" ];
console.log(x.find(/na/)); // Contains 'na'? Outputs: [0]
console.log(x.find(/a/)); // Contains 'a'? Outputs: [0,1,2]
console.log(x.find(/^a/)); // Starts with 'a'? Outputs: [1]
console.log(x.find(/e$/)); // Ends with 'e'? Outputs: [1,2]
console.log(x.find(/pear/)); // Contains 'pear'? Outputs: []
解决方案2:减少,测试
Array.prototype.find = function(regex) {
return this.reduce(function (acc, curr, index, arr) {
if (regex.test(curr)) { acc.push(index); }
return acc;
}, [ ]);
}
let x = [ "banana", "apple", "orange" ];
console.log(x.find(/na/)); // Contains 'na'? Outputs: [0]
console.log(x.find(/a/)); // Contains 'a'? Outputs: [0,1,2]
console.log(x.find(/^a/)); // Starts with 'a'? Outputs: [1]
console.log(x.find(/e$/)); // Ends with 'e'? Outputs: [1,2]
console.log(x.find(/pear/)); // Contains 'pear'? Outputs: []
您可以扩展数组原型以在数组中查找匹配项
Array.prototype.find = function(match) {
var matches = [];
$.each(this, function(index, str) {
if(str.indexOf(match) !== -1) {
matches.push(index);
}
});
return matches;
}
然后你可以像这样在你的数组上调用 find
// returns [0,3]
["banana","apple","orange", "testna"].find('na');
使用正则表达式可以在 javascript 中做到这一点
var searchin = item.toLowerCase();
var str = columnId;
str = str.replace(/[*]/g, ".*").toLowerCase().trim();
return new RegExp("^"+ str + "$").test(searchin);
除了已经说过的所有其他内容之外,您还可以执行以下操作:
var x = ["banana", "apple", "orange"];
var y = [];
for (var i in x) {
if (x[i].indexOf('na') > -1) {
y.push(i);
}
}
结果:y = [0]