Use your left/right keys to browse tutorials
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;
}


Recent shares

More tutorials from Papermashup
Comments
69 discussions around Read URL GET variables with JavaScript
  1. Alejandra says:

    So helpful! Thank you so much

  2. Miguel says:

    I know this is very old, but still…

    There is the case of multiple values where this function is not working correctly (eg: http://papermashup.com/index.php?id=123&page=home&id=234).

    I changed this part:
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    if(vars[key]){
    if(vars[key] instanceof Array){
    vars[key].push(value);
    }else{
    vars[key] = [vars[key], value];
    }
    }else{
    vars[key] = value;
    }
    });

    There is probably a more efficient way of doing it, but the key point is that when you have multiple values you should have an array of values in the vars entry.

  3. Gregg says:

    Quick and easy function to solve the problem.
    Thanks man, exactly what l needed!

  4. Mikael says:

    Although this was written 3,5 years ago it’s still very helpful :) Thank you!

  5. Stef says:

    Thanks, so simply and lhelpful.

  6. Pingback: Retreive $_GET variables in JavaScript from a URL string | Eric Holmes

  7. Ramesh says:

    Awesome exactly what I needed.

  8. Brent says:

    Awesome exactly what I needed.

  9. Akamu Nnamdi Alexander says:

    and then for example code it like so:

    var t = window.$_GET(‘admin’);

  10. Akamu Nnamdi Alexander says:

    you can also try this :

    window.constructor.prototype.$_GET = function(key){
    //alert(this.href);
    var r = {};
    var url = this.location.href;
    var s1 = url.split(‘?’);
    var s2 = s1[1].split(‘&’);
    for (var i in s2){
    var s3 = s2[i].split(‘=’);
    r[s3[0]] = s3[1];
    }
    return r[key];
    };

  11. Hello, its nice article about media print, we all know media is a great source of information.

  12. adit says:

    thanks, good job..

  13. niganj says:

    Great Work.Thanks

  14. James Abuda says:

    Thanks men. Very helpful!!!!

  15. Pingback: Drawing Hats on Monkeys with Mechanical Turk | Monkeyologist

  16. Abdul Jabbar says:

    thanks, good job.. keep it up

  17. Mel Adamei says:

    Beautiful, thank you.

  18. EddyF says:

    caching the results FTW, Kudos.

  19. gusman says:

    nice post.. it work for me

    thank you

  20. modraideja says:

    Great, I just love useful little scripts like this…

  21. kalai says:

    its working.
    thanks

  22. amol says:

    Very hadny code.. Keep sharing..

  23. Biswajit Roy says:

    Thank you. Very nice codes.

  24. Biswajit Roy says:

    Thank you. Very nice code.

  25. vivek says:

    Thanks it helped me…….

  26. Alexis says:

    Genial el código!!

    Greetings from Chile

  27. Emma Davis says:

    Brilliant piece of code, just what I needed. Thank you to the person who wrote the original code.

  28. michelderock says:

    great post (^u^)
    do you know how to add the possibility of not including the anchor in the function call?
    example:
    http://www.mysite.com/index.php?id=123#main_title
    when calling
    var id= getUrlVars()["id"]
    alert(id);
    i got
    123#main_title

  29. Pete says:

    I love it when code just works!

    This is simple and it works – thank you :-)

  30. Laxmi says:

    Thanks…. :)

    Regards,
    Laxmi Damani

  31. alkos333 says:

    The following is a slight modification of your helper method: https://gist.github.com/1771618

    1. It searches only the query part of the string
    2. Does not create arrays or objects
    3. Quits parsing at first match
    4. Returns only the value asked for

  32. Parker says:

    Thanks for posting ~

  33. Chris says:

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

  34. Talakisew Binor says:

    Very interesting, easy and valuable snippet.
    Thanks,

  35. Pete says:

    This worked like magic! Thank you for sharing :)

  36. Correction:

    Lines 04 and 05 in first snippet must be:

    alert(first);
    alert(second);

  37. CaoS says:

    Thanks :)

    Best regards :)

  38. Luka says:

    Thanks. It helped me a lot!!

  39. Falguni says:

    Thanks for snippet.it is very useful and easy.

  40. Vivek Shrivastava says:

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

    Thanks

  41. 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.

  42. 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.

  43. Rush says:

    You saved my day.

  44. Nox says:

    I love you ^^
    you made my day

  45. 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

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

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

  48. Peter says:

    thanks for the code

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

  50. stevej says:

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

  51. jared says:

    “Remember you need to include the jQuery framework.”

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

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

  53. Ledopsi says:

    What about window.location.search ?

  54. Kevin says:

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

  55. 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

  56. Pingback: uberVU - social comments

  57. 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

  58. 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>



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 contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

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 please get in touch via the contact link below for 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.