I would like to extend the Javascript built-in Array object by addind a new method: searchByRegexp
Basically the method will get a regexp as input and will return:
_ a string representing the element of the array that matches the regexp (if more than one match, the first one will be returned)
_ an empty string if none of the elements matches the regular expression.
2 Answers 2
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/>");
});
As of today, using Google Chrome, the provided solution breaks the iteration over the array.
After Array.prototype.searchByRegexp = function ..., if you iterate with for (var k in arrayInstance), the value searchByRegexp will be in the keys, not only the real array keys.
To prevent that you should use Object.defineProperty(Array.prototype, ...
Object.defineProperty(Array.prototype, 'searchByRegexp', {
value: 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 "";
},
enumerable: false
});
Enumerable.grepfor example.