问题描述
我希望下面的if
语句在数组中包含功能"时提醒是",而不管它是大写还是小写.
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 very familiar with Regular Expressions, so perhaps my regular expression is wrong..
var myArray = ["featured", "foo", "bar"];
if( $.inArray(/featured/i, myArray) > -1 ){
alert('yes!');
}
推荐答案
我不认为$.inArray
支持正则表达式,但是您可以使自己的函数支持.
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;
};
正在运行的演示: http://jsfiddle.net/jfriend00/H4Y9A/
您甚至可以覆盖现有的inArray以使其可选地"支持正则表达式,同时仍保留其正则功能:
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);
}
};
})();
正在运行的演示: 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.
这篇关于我可以在jQuery.inArray()中使用正则表达式吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!