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

后端 未结 5 530
刺人心
刺人心 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: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.

提交回复
热议问题