Syntactic sugar: RexExp.exec with callbacks
The RegExp.exec method returns an array of results when there’s a match or null when there’s none. I often find myself coding the same check over and over again:
var result = /(.+)=(.+)/.exec("name=value");
if (result) {
console.log(result[1] + " = " + result[2]);
}
It would make life easier if exec accepted a callback method as the second argument (and then a scope as the third):
/(.+)=(.+)/.exec("name=value", function (str, name, value) {
console.log(name + " = " + value);
});
The added benefit of this is, instead of accessing the results via error-prone indices, we get to access them with named arguments inside the callback.
Here’s an extension to the core exec function that adds callback support while simultaneously retaining the original calling mechanism:
RegExp.prototype.exec = (function (exec) {
return function (str, callback, scope) {
var results = exec.call(this, str);
if (arguments.length > 1 && results) {
callback.apply(scope, results);
} else {
return results;
}
};
})(RegExp.prototype.exec);