Last active
May 22, 2018 06:41
-
-
Save sairion/7065921 to your computer and use it in GitHub Desktop.
Slice URL and get param values via JavaScript
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
//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
Thanks for the code!!!
. I do a little modifications because it´s dosent work´s fine for my URL, but now work´s !!! And also work´s with realtive and absolutes URL, is perfect your code XD.
My code with the little modification:
var urlmap=splitCurrentURL("geo.html?name=Futbolmania%20Madrid&lat=40.41687784026351&lng=-3.7024784088134766&state=Madrid&address=Pl.%20de%20la%20Puerta%20del%20Sol,%205&postalCode=28013&city=Madrid/");
function splitCurrentURL(parse){
//query given index.html?this=true&that=good;
var url = document.createElement('a');
url.href = parse; //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 nameClear = params.name.split("%20");
var addressClear = params.address.split("%20");
return {
name: nameClear,
lat: params.lat,
lng: params.lng,
state: params.state,
adress: addressClear,
postalCode: params.postalCode,
city: params.city
};
}