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
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
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/
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!" );
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
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.