Skip to content

Instantly share code, notes, and snippets.

@SethVandebrooke
Last active June 20, 2018 17:40
Show Gist options
  • Save SethVandebrooke/d0676eaeb03d920ac6c6d26a24e5aecb to your computer and use it in GitHub Desktop.
Save SethVandebrooke/d0676eaeb03d920ac6c6d26a24e5aecb to your computer and use it in GitHub Desktop.
Get URL data easily
const parseURL = function(char) {
var url = window.location.href, data = {};
char = !!char ? char === "?" || char === "#" ? char : "check" : "check";
if (char==="check") {
char = url.includes("?") ? "?" : url.includes("#") ? "#" : false;
if (char === false) { return false; }
}
url = url.substring(url.indexOf(char)+1,url.length);
if (url.includes("=")) {
var kv = url.split("&");
kv.forEach(function(e){
data[e.split("=")[0]] = e.split("=")[1];
});
return kv[0].split("=").length > 1 ? data : url;
}
return url;
};
const URLparams = function () {
var str = location.search.substring(1).split("&"), params = {};
for (var i = 0; i < str.length; i++) {
var p = str[i].split("=");
params[p[0]] = p[1];
}
return params;
}
/*
parseURL() checks to see if the current url has a ? or a # and returns an object consisting of the keys and values defined after
the chosen symbol.
The symbol can be specifically defined by passing ? or # as a parameter to the function like so:
parseURL("#") || parseURL("?")
if the function finds no data to present automatically, it will return false.
if it a symbol is specified but there are no key value pairs, it will return whatever follows the specified symbol
if the specified symbol does not exist in the url, the full url will be returned.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment