In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.
Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
Calling getUrlVars() function would return you the following array:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
To get a value of first parameter you would do this:
var first = getUrlVars()["me"]; // To get the second parameter var second = getUrlVars()["name2"];
To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
Now, if you include the above code in your javascript file, you can get URL parameter values in the following way:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name');
That’s it! You might also find the following jQuery related articles on this blogs interesting:
- Cross-domain AJAX querying with jQuery
- Javascript for() loop vs jQuery .each() performance comparison
- Create jQuery custom selectors with parameters
- JavaScript / jQuery password generator



13 comments:
Shouldn't you cache the decoded vars?
I don't really see the point of making this a jquery plugin in this case, since it doesn't take jQuery or DOM elements and doesnt return them either.
Nonetheless, This is by far the cleanest implementation of this utility I have seen.
Also, jQuery will let you go back the other way too:
$.param({
me: "myValue",
name2: "someOtherValue"
});
returns "me=myValue&name2=someOtherValue"
This is really nice for caching the results of jQuery plugins that take objects as parameters. Usually, if you try to say cache[obj] = foo obj.toString will be called and you will be left with "[object Object]", which is not too helpful, but $.param() handles everything cleanly and quickly. So, now cache[$.param(obj)] = foo works out perfectly.
Thanks !!
Just one line is enough inside getUrlVars():
return window.location.href.slice(window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/);
Take care
That's pretty sweet. I'm in the need for just this bit of code. Thanks! :)
Shane
I was going to reply to this post with a regex solution, which I think is much more elegant. However, someone has obviously beat me to it:
http://ejohn.org/blog/search-and-dont-replace/
Er, I posted too soon. The page I linked to wasn't solving this exact problem. Here's the solution that solves this problem:
function getUrlParameters() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
you are confusing location.search and location.hash
here is an example i built for a framework that extracts both search and hash
var Params = {
/*
Get
-------------------------------
walk through window.location.search and window.location.hash
generate object (result) from iteration
*/
Get:function()
{
result = {};
request = {
search:window.location.search.slice(1, window.location.search.length),
hash:window.location.hash.slice(1, window.location.hash.length)
}
// check
for(type in request)
{
if(request[type] != "")
{
var x = request[type].split("&");
for(i in x)
{
var y = x[i].split("=");
var prop = y[0];
var value = y[1];
result[prop] = value;
}
}
}
return result;
}
}
where result will be an object as such
result = {
search:{
prop:value,...
},
hash:{
prop:value,...
},
}
ps: love your articles
addons.32teeth@gmail.com
I know this is completely unrelated but based on your understanding of jquery, please indulge me an see if you can help me...
I have this code
jQuery(document).ready(function() {
$('a').click(function() {
...
I have a lot of a (=link) tags generated dynamically after an Ajax call that I tug inside a div tag but for the life of me they do not get selected based on the event above...can you help me out? thanks!
Looks great!! But how to call an extension in jquery ?
Thanks Alex
This is a great bit of code, thanks a lot. I added the code in a separate js file and works well.
Would be nice to add decodeURI before slice url
Excellent article.
But after reading the following
http://asimilia.wordpress.com/2008/12/17/jquery-extend-confusion/
I have little bit confusion... which one is correct in our example?
Post a Comment