Read URL GET variables with JavaScript

28 October 2009| 20 Comments| Print

Yesterday I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code on Snipplr. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.

So as an example if we had the following url with the javascript at the bottom in place.

http://papermashup.com/index.php?id=123&page=home

All we’d need to do to get the parameters id and page are to call this:

var first = getUrlVars()["id"];
var second = getUrlVars()["page"];

alert(id);
alert(page);

The Code

function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

UPDATE: this post was originally titled ‘Read URL GET variables with jQuery’ but a few of you pointed out that this is in fact just plain JavaScript. Totatlly my mistake. I planned to originally write a tut on reading url variables with jQuery. But at the last minute I found the 3 lines of code above that completely solved my problem, trouble was i forgot to adjust the title.


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

20 Comments

  • Balaji

    Have you given any thoughts to jQuery Form Highlighting? I’ve been hard pressed to find good resources, and judging from this article I’m guessing you may have something valuable to say. Thanks in advance!

  • Ashley

    @Balaji have you seen my article on form highlighting?

  • Elijah Manor

    Here is another article that I ran across to do the same thing… code is slightly different, but end result is same.

    FYI, I will be tech tweeting your blog post today ;) Thnx

  • uberVU - social comments

    Social comments and analytics for this post…

    This post was mentioned on Twitter by metoikos: Read URL GET variables with jQuery | Papermashup.com http://ff.im/-aGQ9b...

  • Davinder

    Hello,
    Lovely article but my question is: What’s faster using Jquery’s GET variables or using PHP’s GET variables?
    Thank You

  • Kevin

    I may be missing something here, but isn’t this just plain Javascript?

  • Ledopsi

    What about window.location.search ?

  • Paul Sayre

    Here is a way to do the same thing, only caching the results so the regex is only run once.


    var getUrlVars = (function() {
    var vars;
    return function() {
    if(vars !== undefined) return vars;
    vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
    return vars;
    }
    })();

  • Hongpak

    Woow! and Thanks

  • jared

    “Remember you need to include the jQuery framework.”

    I think not. That’s plain, old Javascript.

  • Ashley

    @jared thanks for pointing that out, quite a few people contacted me about that. My mistake see the updated post above. ;)

  • stevej

    If a key repeats (e.g. checkboxes), only the value of the last pair will be available.

  • stevej

    function getUrlVars(url) {
    var vars = {};
    var url = url? url.toString().split(‘?’).pop()
    : window.location.search.slice(1);
    url.replace(
    /([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
    key = unescape(key);
    if (key) {
    value = unescape(value);
    if (key in vars) {
    if (vars[key] instanceof Array)
    vars[key].push(value);
    else
    vars[key] = [vars[key], value];
    } else
    vars[key] = value;
    }
    });
    return vars;
    }

  • Serdar Alten Şimşek

    thank you

  • Peter

    thanks for the code

  • molokoloco

    Ok, thank, great regex :)
    here the code to integrate with jQuery :)


    $.extend({
    getUrlVars: function() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
    return vars;
    }
    });
    // var name = $.getUrlVars()['name'];

  • Ashley

    @molokoloco, Thanks!

  • Chris M

    Anyone looking to read the #Anchor from a url using javascript such as index.html#welcome try this.

    var urlanchor = self.document.location.hash.substring(1);

  • jon mortimer

    Sorry for this post since it is a year old but I have a question. I am a faily newbie and appreciate any assistance. Firstly, where do I place this code? I’m assuming I can put it into my html file within javascript brackets. I’ve done that — how do I use the variable though, since it is outside the “function”? Obviously if I just place the variables on an html page it will just display as text.

  • Ashley

    Hi Jon,

    No Problem, you simply need to add both code snippets between script tags within you page head then save your page and upload it to your web server and visit the page. at first you wont see anything but then add at the end of the URL in your browser ?id=1234 then you should see 1234 alerted. I’ve made a typo in the code snippet. the alerts should be alert(first); alert(second); the ‘id’ and ‘page’ can be any get variable that you want to pick up with javascript.

    Hope that helps

    Ashley

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here