Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electron0zero/96e00146d2e778b8c0eecf8838461b90 to your computer and use it in GitHub Desktop.
Save electron0zero/96e00146d2e778b8c0eecf8838461b90 to your computer and use it in GitHub Desktop.
Slice URL and get param values via JavaScript
//using String.split to split and assign Object
function splitCurrentURL(){
//query given index.html?this=true&that=good;
var url = location.href.split("?")[1]; // this=true&that=good;
params = {}; //init param obj
url = url.split("&"); // ['this=true','that=good']
for(var i = 0; i<url.length; i++){
var split_cache = url[i].split("="); // ['this','true'], ...
params[split_cache[0]] = split_cache[1]; // {this:true}, ...
}
return params; // {this:"true", that:"good"}
}
//alternative method using HTMLAnchorElement's basic API (https://gist.github.com/jlong/2428561)
function splitCurrentURL(){
//query given index.html?this=true&that=good;
var url = document.createElement('a');
url.href = location.href; //assign current url into HTMLAnchorElement
url = url.search.slice(1); //to cut "?" char
params = {};
url = url.split("&"); // ['this=true','that=good']
for(var i = 0; i<url.length; i++){
var split_cache = url[i].split("="); // ['this','true']
params[split_cache[0]] = split_cache[1]; // {this:true}
}
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment