Skip to content

Instantly share code, notes, and snippets.

@rudylattae
Created January 16, 2014 00:28
Show Gist options
  • Save rudylattae/8447557 to your computer and use it in GitHub Desktop.
Save rudylattae/8447557 to your computer and use it in GitHub Desktop.
var ourl = (function () {
function ourl(url) {
url = url || window.location.href;
return new ObjectifiedUrl(url);
};
ourl.parse = parseUrl;
function ObjectifiedUrl(url) {
this._url = url;
}
ObjectifiedUrl.prototype.toString = function () {
return this._url;
};
ObjectifiedUrl.prototype.param = function (name) {
if (!this._parsedUrl) this._parseUrl();
return this._parsedUrl.params[name];
};
ObjectifiedUrl.prototype.attr = function (name) {
if (!this._parsedUrl) this._parseUrl();
return this._parsedUrl[name];
};
ObjectifiedUrl.prototype.toJS = function () {
if (!this._parsedUrl) this._parseUrl();
return this._parsedUrl;
};
ObjectifiedUrl.prototype._parseUrl = function () {
if (!this._parsedUrl)
this._parsedUrl = parseUrl(this._url);
};
// REF: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
// For alternatives, see: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
function splitUrlParams(queryPart) {
if (typeof queryPart === "undefined") return {};
queryPart = queryPart.split('?') ? queryPart.split('?')[1] : queryPart;
var a = queryPart.split('&'),
b = {},
i = 0;
var limit = a.length;
for (; i < limit; ++i) {
var p = a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
}
// REF: http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
// For alternatives, see: https://github.com/websanova/js-url https://github.com/allmarkedup/purl
function parseUrl(url) {
var result = {},
anchor = document.createElement('a'),
keys = 'protocol hostname host pathname port search hash href'.split(' ');
anchor.href = url;
for (var k in keys) {
var me = keys[k];
result[me] = anchor[me];
}
result.source = url;
result.params = splitUrlParams(result.search);
return result;
};
// exports
return ourl;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment