Thursday, December 30, 2010

Getting all the URL params in Javascript

I've been updating a lot of href's lately and found these functions to be very handy. They basically take all the pars in a string and put them in a JS object. There is other functions out there that get you 1 url param, but I wanted them all. Reason being, is I need to see if that param exists and do some more checks on it for business logic, then take all the pars and turn then into a querystring and add them back to href again.


getURLParameters = function(url){

var results = {};

if(url == ""){
var url = window.document.URL.toString();
}
if (url.indexOf("?") > 0){
var splitURL = url.split("?");
params = splitURL[1].split("&");

for (var i=0;i var param = params[i].split("=");
if (param[1] != "")
results[param[0]] = unescape(param[1]);
else
results[param[0]] = "";
}

}

return results;
};
getURL = function(url){

if(url == ""){
var url = window.document.URL.toString();
}

if(url.indexOf("?") > 0){
var splitURL = url.split("?");
url = splitURL[0];
}

return url;
};


getURL() actually serves two purposes. If a url isn't passed in get the current url. And it also cleans off all of params so all you get the base url.

1 comment:

  1. Hi there mates, its enormous article about teaching and fully defined, keep it up all the time. Source: Finding The Best Encryption Software & You Knew How To How To Encrypt A Password For Free But You Forgot. Here Is A Reminder.

    ReplyDelete