Read URL GET variables with JavaScript

Read URL GET variables with JavaScript

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on October 28, 2009

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(first);
alert(second);

The Code

function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}
More tutorials from Papermashup
Comments
33 discussions around Read URL GET variables with JavaScript
  1. Chris says:

    Shouldn’t it be alert(first) and alert(second)?

  2. Talakisew Binor says:

    Very interesting, easy and valuable snippet.
    Thanks,

  3. Pete says:

    This worked like magic! Thank you for sharing :)

  4. Correction:

    Lines 04 and 05 in first snippet must be:

    alert(first);
    alert(second);

  5. CaoS says:

    Thanks :)

    Best regards :)

  6. Luka says:

    Thanks. It helped me a lot!!

  7. Falguni says:

    Thanks for snippet.it is very useful and easy.

  8. Vivek Shrivastava says:

    Hello Friends,
    I want the java script code to get all bookmarked url’s .

    Thanks

  9. masterKen02 says:

    Awesome Post. I actually use this technique to solve a client problem instantly over the phone. It was a real live saver. Thanks.

  10. I enjoyed your article, it was informative and entertaining. I don’t know much about this trackback thing I’ll link to your site from my blog instead. Great stuff – I’ll keep an eye out for more.

  11. Rush says:

    You saved my day.

  12. Nox says:

    I love you ^^
    you made my day

  13. jon mortimer says:

    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 says:

      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

  14. Chris M says:

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

  15. molokoloco says:

    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'];

  16. Peter says:

    thanks for the code

  17. stevej says:

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

  18. stevej says:

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

  19. jared says:

    “Remember you need to include the jQuery framework.”

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

  20. Paul Sayre says:

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

  21. Ledopsi says:

    What about window.location.search ?

  22. Kevin says:

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

  23. Davinder says:

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

  24. Pingback: uberVU - social comments

  25. Elijah Manor says:

    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

  26. Balaji says:

    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!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.