Interesting little dilemma this morning (although, in the context of anything brought up on September the 11th, “dilemma” is extraordinarily relative): How much should one rely on built-in language support for certain functions, vs. rolling your own solution that may be a little closer to the metal?
I’m normally a fan of Agile/XP mantra the simplest thing that could possibly work, but the key word in that sentence is “work”. And considering that the language in question is JavaScript, we have the makings of a little bit of drama.
Consider these two little bits of JavaScript code:
var loc = window.location;
var pat = "(htt(p|ps):)//([^/]*)(/.*)";
var regex = new RegExp(pat);
var url = window.location.href;
var arr = regex.exec(url);
var protocol = arr[1];
var domain = arr[3];
var remainder = arr[4];
var loc = window.location;
var protocol = window.location.protocol;
var domain = window.location.host;
var remainder = window.location.pathname + window.location.search;
In theory, these two snippets should result in the same values for the protocol, domain, and remainder variables. In theory. But (a) I’m old enough to remember when JS support across browsers was incoherently inconsistent; and (b) I’m still not sold on the current stability of JavaScript within browsers, anyway.
For example: window.location.host contains the port (if specified). Why not just use the port property? Not all browsers support window.location.origin. Why?
For now, I’m going to go with the regex version, because I figure it insulates me from any JavaScript changes. I’m really just doing string parsing, in effect, and even though the code is twice as long I feel more comfortable.
What would you do?
