Last active
June 18, 2018 15:05
-
-
Save rose-pace/8139751b94de446e7a19e7fb32e7c9d8 to your computer and use it in GitHub Desktop.
JavaScript helper object for dealing with urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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