Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@Alexiades

This comment has been minimized.

Copy link

commented May 10, 2015

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 split_cache = url[i].split("="); // ['this','true']
//var split_cache = url[i].split("20%"); // ['this','true']
params[split_cache[0]] = split_cache[1]; // {this:true}

}
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
};
}

window.alert(urlmap.name);
window.alert(urlmap.adress);

window.alert(urlmap.lng);
window.alert(urlmap.state);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.