在Javascript中搜索字符串数组时,我可以使用通配符吗? [英] Can I use wildcards when searching an array of strings in Javascript?

查看:90
本文介绍了在Javascript中搜索字符串数组时,我可以使用通配符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串数组:

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

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

is there a built in shortcut for performing wildcard searches?

ie。,也许

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


推荐答案

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

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

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 filter method:

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

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

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

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

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

它确实提供了允许您指定有效RegExp字符串的灵活性,尽管。

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

x.findReg('a'); // returns all three
x.findReg("a$"); // returns only "banana" since it's looking for 'a' at the end of the string.

这篇关于在Javascript中搜索字符串数组时,我可以使用通配符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆