Can I use a Regular Expression within jQuery.inArray()

后端 未结 5 531
刺人心
刺人心 2021-01-07 06:42

I would like the following if statement to alert \'yes\' if \'featured\' is in array, regardless of whether it is uppercase or lowercase.

I\'m also not

相关标签:
5条回答
  • 2021-01-07 07:09

    Version using Javascript exec and forEach. It achieves the same but does not use inArray.

    var myArray = ["featured", "foo", "bar"];
    
    var exp = /featured/i;
    
    myArray.forEach( function(value){
    
       if( exp.exec(value) ){
        alert("yes");
       }
    
    } );
    

    Fiddle

    0 讨论(0)
  • 2021-01-07 07:16

    No, I don't think so.

    This is how I would to it, using ($.each and match()):

    var myArray = ["featured", "foo", "bar"];
    
    
    $.each(myArray,function(index,value){
        if(value.match(/featured/i) !== null){
            alert("Yes!");
            return false;
        }
    });
    

    on JSFIDDLE: http://jsfiddle.net/QGtZU/

    0 讨论(0)
  • 2021-01-07 07:20

    You can use $.grep to filter the array and then check the length:

     if ( $.grep( myArray, function (e, i ){ return /featured/i.test(e); }).length > 0 )
        alert( "YES!" );
    
    0 讨论(0)
  • 2021-01-07 07:33

    An array is not a string, but you can make it a string, by using toString

    if(/featured/.test(myArray.toString())){
        alert('yes!');
    }
    

    WORKING DEMO

    0 讨论(0)
  • 2021-01-07 07:34

    I don't think $.inArray supports regular expressions, but you could make your own function that does.

    $.inArrayRegEx = function(regex, array, start) {
        if (!array) return -1;
        start = start || 0;
        for (var i = start; i < array.length; i++) {
            if (regex.test(array[i])) {
                return i;
            }
        }
        return -1;
    };
    

    Working demo: http://jsfiddle.net/jfriend00/H4Y9A/


    You could even override the existing inArray to make it "optionally" support regular expressions while still retaining its regular functionality:

    (function() {
        var originalInArray = $.inArray;
        $.inArray = function(regex, array, start) {
            if (!array) return -1;
            start = start || 0;
            if (Object.prototype.toString.call(regex) === "[object RegExp]") {
                for (var i = start; i < array.length; i++) {
                    if (regex.test(array[i])) {
                        return i;
                    }
                }
                return -1;
            } else {
                return originalInArray.apply(this, arguments);
            }
        };
    })();
    

    Working demo: http://jsfiddle.net/jfriend00/3sK7U/

    Note: the one thing you would lose with this override is the ability to find a regular expression object itself in an array.

    0 讨论(0)
提交回复
热议问题