在 Javascript 中搜索字符串数组时可以使用通配符吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12695594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:03:05  来源:igfitidea点击:

Can I use wildcards when searching an array of strings in Javascript?

javascript

提问by blueberryfields

Given an array of strings:

给定一个字符串数组:

x = ["banana","apple","orange"]

is there a built in shortcut for performing wildcard searches?

是否有用于执行通配符搜索的内置快捷方式?

ie., maybe

即,也许

x.indexOf("*na*") //returns index of a string containing the substring na

回答by Shmiddty

Expanding on Pim's answer, the correct way to do it (without jQuery) would be this:

扩展 Pim 的答案,正确的方法(没有 jQuery)是这样的:

Array.prototype.find = function(match) {
    return this.filter(function(item){
        return typeof item == 'string' && item.indexOf(match) > -1;
    });
}

But really, unless you're using this functionality in multiple places, you can just use the existing filtermethod:

但实际上,除非您在多个地方使用此功能,否则您只能使用现有filter方法:

var result = x.filter(function(item){
    return typeof item == 'string' && item.indexOf("na") > -1;            
});

The RegExp version is similar, but I think it will create a little bit more overhead:

RegExp 版本类似,但我认为它会产生更多的开销:

Array.prototype.findReg = function(match) {
    var reg = new RegExp(match);

    return this.filter(function(item){
        return typeof item == 'string' && item.match(reg);
    });
}

It does provide the flexibility to allow you to specify a valid RegExp string, though.

不过,它确实提供了允许您指定有效 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.

回答by Stephen Quan

Extending on @Shmiddty's answer, here are useful JavaScript ideas:

扩展@Shmiddty 的回答,这里有一些有用的 JavaScript 想法:

  • Extend Array with a new method: Array.prototype.method = function(arg) { return result; }
  • Filter arrays using: Array.filter(function(e) { return true|false; })
  • Apply formula to elements in an array: Array.map(function(e) { return formula(e); })
  • Use regular expressions: either /.*na.*/or new Regex('.*na.*')
  • Use regular expressions to match: var result = regex.test(input);
  • Use Array.prototype.reduceto aggergate a result after running a function on every element of an array
  • 使用新方法扩展 Array: 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.*')
  • 使用正则表达式匹配: var result = regex.test(input);
  • 在对数组的每个元素运行函数后,使用Array.prototype.reduce来聚合结果

i.e. I prefer the input argument to be a regex, so, it gives you either:

即我更喜欢输入参数是一个正则表达式,所以,它给你:

  • A short but universal pattern matching input,
    • e.g. contains, starts with, ends width, as well as more sophisticated matches
  • The ability to specify an input pattern as a string
  • 一个简短但通用的模式匹配输入,
    • 例如包含、开始于、结束宽度,以及更复杂的匹配
  • 将输入模式指定为字符串的能力

SOLUTION 1: filter, test, map and indexOf

解决方案 1:过滤器、测试、映射和 indexOf

Array.prototype.find = function(regex) {
  var arr = this;
  var matches = arr.filter( function(e) { return regex.test(e); } );
  return matches.map(function(e) { return arr.indexOf(e); } );
};
var 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: [0]
console.log(x.find(/e$/)); // Ends with 'e'? Outputs: [1,2]
console.log(x.find(/pear/)); // Contains 'pear'? Outputs: []

SOLUTION 2: reduce, test

解决方案2:减少,测试

Array.prototype.find = function(regex) {
  return this.reduce(function (acc, curr, index, arr) {
    if (regex.test(curr)) { acc.push(index); }
    return acc;
  }, [ ]);
}
var 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: [0]
console.log(x.find(/e$/)); // Ends with 'e'? Outputs: [1,2]
console.log(x.find(/pear/)); // Contains 'pear'? Outputs: []

回答by Pim

You can extend the array prototype to find matches in an array

您可以扩展数组原型以在数组中查找匹配项

Array.prototype.find = function(match) {
    var matches = [];
    $.each(this, function(index, str) {
        if(str.indexOf(match) !== -1) {
            matches.push(index);
        }
    });
    return matches;
}

You can then call find on your array like so

然后你可以像这样在你的数组上调用 find

// returns [0,3]
["banana","apple","orange", "testna"].find('na');

回答by Shailesh B. Rathi

using regex can do this in javascript

使用正则表达式可以在 javascript 中做到这一点

var searchin = item.toLowerCase();
var str = columnId;
str = str.replace(/[*]/g, ".*").toLowerCase().trim();
return new RegExp("^"+ str + "$").test(searchin);

回答by bryc3m0nk3y

In addition to everything else that has been said, you can do this:

除了已经说过的所有其他内容之外,您还可以执行以下操作:

var x = ["banana", "apple", "orange"];
var y = [];
for (var i in x) {
    if (x[i].indexOf('na') > -1) {
        y.push(i);
    }
}

Results: y = [0]

结果:y = [0]