Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 562
blueberryfields Avatar asked Oct 02 '12 17:10

blueberryfields


1 Answers

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;            
});

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);
    });
}

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.
like image 195
Shmiddty Avatar answered Sep 21 '22 12:09

Shmiddty