Skip to content

Instantly share code, notes, and snippets.

@rose-pace
Last active June 18, 2018 15:05
Show Gist options
  • Save rose-pace/8139751b94de446e7a19e7fb32e7c9d8 to your computer and use it in GitHub Desktop.
Save rose-pace/8139751b94de446e7a19e7fb32e7c9d8 to your computer and use it in GitHub Desktop.
JavaScript helper object for dealing with urls
var UrlHelper = function (location) {
this.protocol = '';
this.host = '';
this.path = '';
this.queryValues = {};
this.initQueryValues = function (search) {
var vals = {};
if (search) {
var pairs = search.substr(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
vals[pair[0]] = pair[1];
}
}
return vals;
};
this.getSearchString = function () {
var search = "?";
if (this.queryValues) {
for (var key in this.queryValues) {
search += key + "=" + this.queryValues[key] + "&";
}
}
return search.substr(0, search.length - 1); //drop trailing &
};
this.toString = function () {
return this.protocol + "//" + this.host + this.path + this.getSearchString();
};
//init
if (location) {
this.protocol = location.protocol;
this.host = location.host;
this.path = location.pathname;
this.queryValues = this.initQueryValues(location.search);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment