Function.prototype.method = function(name, func) {
if (!this.prototype[name]) { this.prototype[name] = func; return this; }
}
RegExp.method("compose", function( parts ) {
var i, r="";
for( i=0; i < parts.length; i+=1) {
r += (is_array( parts[i]) ? "("+RegExp.prototype.compose(parts[i])+")" : parts[i] );
}
return r;
});
Then suppose we call this new method as so:
var re=(new RegExp).compose(
[ "^",
[ "?:", ["[A-Za-z]+"], ":"],
"?"
]);
What we get is the composed string with array nesting used to imply the presence of groups. Note that the regular expression may now be broken up into multiple lines, and commented heavily, but you still get ^?:([A-Za-z]):)?. A similar technique using array stuffing and the join method is quite useful for creating page output in a manner that avoids most of the output coding. The array is a template, and one just specifies a single join and output command:
var pg = [
"Mushrooms
"
"placeholder",
"foo"
];
pg.push("Some stuff
");
document.getElementById("bar").innerHTML = pg.join();
No comments:
Post a Comment