Quick and dirty (fiddle for your fiddling pleasure):
Array.prototype.searchByRegexp = function (rx) {
for(var i = 0, ln = this.length; i < ln; i++) {
// test item i
if(rx.test(this[i])) {
return this[i] + "";
}
}
// return an empty string if no matches are found
return "";
}
However, you may wish to implement more general methods instead...
Array.prototype.find = function(delegate) {
for(var i = 0, ln = this.length; i < ln; i++) {
if(delegate(this[i])){
return this[i];
}
}
return null;
}
Array.prototype.findAll = function(delegate) {
var results = [];
for(var i = 0, ln = this.length; i < ln; i++) {
if(delegate(this[i])){
results.push(this[i]);
}
}
return results ;
}
Array.prototype.each = function (delegate) {
for (var i = 0, ln = this.length; i < ln; i++) {
delegate(this[i], i);
}
}
... which could then perform regex comparison like so:
// test values
var sizes = ["Small", "Medium", "Large", "Extra-Large", "Extra-Extra-Large"];
// Print single value or blank
document.write(sizes.find(function(size){
return /large/i.test(size);
}) || "");
// horizontal rule to separate our results
document.write("<hr/>");
// Print all matches
sizes.findAll(function(size){
return /large/i.test(size);
}).each(function(size){
document.write(size + "<br/>");
});
Enumerable.grepfor example.