Papermashup

Subscribe


Tweets


"@burgerbeartom @kycutwilson finally got around to using my free burgers for life! And we weren't disappointed. http://t.co/nJ6p2nLtg4"

@ashleyford 1 week ago

"RT @MAA: Insight from @CommunicatorHQ on the need for brands to take a long view on social responsibility http://t.co/4wWA3A2TOc"

@ashleyford 2 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Read URL GET variables with JavaScript

A simple function to retrieve values in JavaScript passed through a URL

AshleyAshley

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

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 77
  • ABM Abdul Muttalib
    Posted on

    ABM Abdul Muttalib ABM Abdul Muttalib

    Reply Author

    Awesome its solved my problem. Thanks a lot


  • Mark Vakarchuk
    Posted on

    Mark Vakarchuk Mark Vakarchuk

    Reply Author

    can some one explain how to use this function? i cant figure it out for some reason…


  • pamela
    Posted on

    pamela pamela

    Reply Author

    dear all

    I tried the below code :
    function getUrlVars()
    {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf(‘?’) + 1).split(‘&’);
    //var hashes = window.location.href.valueOf().split(‘?’).slice(1)[0].split(‘&’);
    for(var i = 0; i < hashes.length; i++)
    {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
    }
    return vars;
    }
    function test()
    {
    //var hash =getUrlVars();
    //alert(hash['hello']);

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

    but I am getting 'undefined' how to solve it?
    Please help


  • Andy
    Posted on

    Andy Andy

    Reply Author

    Hi, this is superb.
    Do you have a regex for it to pass decimals instead of text?
    I need to pass values like 102.34, -35.76, 3.876

    Any help would be much appreciated.


  • Allison C
    Posted on

    Allison C Allison C

    Reply Author

    Thanks! This helped a lot


  • Lodge Discounted (Hotels_Discount) on Tweets
    Posted on

    Lodge Discounted (Hotels_Discount) on Tweets Lodge Discounted (Hotels_Discount) on Tweets

    Reply Author

    І’m extremely inspired along with your writing abilities and also with the structure in your weblog. Is that this a paid subject matter or did you customize it yourself? Anyway stay up the nice high quality writing, it is rare to peer a nice blog like this one nowadays..

    my web blog … Lodge Discounted (Hotels_Discount) on Tweets


  • nurrohman
    Posted on

    nurrohman nurrohman

    Reply Author

    thank you so much..


  • Ken Engström
    Posted on

    Ken Engström Ken Engström

    Reply Author

    Hello

    Awesome snippet, really liked it but there is a small glitch in the regex.
    Old regex /[?&]+([^=&]+)=([^&]*)/gi
    New regex /[?&]+([^=&]+)=([^&]*?)[#.]/gi

    adds support for hash links (#)


  • Alejandra
    Posted on

    Alejandra Alejandra

    Reply Author

    So helpful! Thank you so much


  • Miguel
    Posted on

    Miguel Miguel

    Reply Author

    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.


  • Gregg
    Posted on

    Gregg Gregg

    Reply Author

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


  • Mikael
    Posted on

    Mikael Mikael

    Reply Author

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


  • xx
    Posted on

    xx xx

    Reply Author

    thanks


  • Stef
    Posted on

    Stef Stef

    Reply Author

    Thanks, so simply and lhelpful.


  • Ramesh
    Posted on

    Ramesh Ramesh

    Reply Author

    Awesome exactly what I needed.


  • xyz
    Posted on

    xyz xyz

    Reply Author

    thanks


  • Brent
    Posted on

    Brent Brent

    Reply Author

    Awesome exactly what I needed.


  • Akamu Nnamdi Alexander
    Posted on

    Akamu Nnamdi Alexander Akamu Nnamdi Alexander

    Reply Author

    and then for example code it like so:

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


  • Akamu Nnamdi Alexander
    Posted on

    Akamu Nnamdi Alexander Akamu Nnamdi Alexander

    Reply Author

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


  • octonauts gup b
    Posted on

    octonauts gup b octonauts gup b

    Reply Author

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


  • adit
    Posted on

    adit adit

    Reply Author

    thanks, good job..


  • niganj
    Posted on

    niganj niganj

    Reply Author

    Great Work.Thanks


  • James Abuda
    Posted on

    James Abuda James Abuda

    Reply Author

    Thanks men. Very helpful!!!!


  • Abdul Jabbar
    Posted on

    Abdul Jabbar Abdul Jabbar

    Reply Author

    thanks, good job.. keep it up


  • Mel Adamei
    Posted on

    Mel Adamei Mel Adamei

    Reply Author

    Beautiful, thank you.


  • EddyF
    Posted on

    EddyF EddyF

    Reply Author

    caching the results FTW, Kudos.


  • gusman
    Posted on

    gusman gusman

    Reply Author

    nice post.. it work for me

    thank you


  • modraideja
    Posted on

    modraideja modraideja

    Reply Author

    Great, I just love useful little scripts like this…


  • kalai
    Posted on

    kalai kalai

    Reply Author

    its working.
    thanks


  • amol
    Posted on

    amol amol

    Reply Author

    Very hadny code.. Keep sharing..


  • Biswajit Roy
    Posted on

    Biswajit Roy Biswajit Roy

    Reply Author

    Thank you. Very nice codes.


  • Biswajit Roy
    Posted on

    Biswajit Roy Biswajit Roy

    Reply Author

    Thank you. Very nice code.


  • vivek
    Posted on

    vivek vivek

    Reply Author

    Thanks it helped me…….


  • Alexis
    Posted on

    Alexis Alexis

    Reply Author

    Genial el código!!

    Greetings from Chile


  • Emma Davis
    Posted on

    Emma Davis Emma Davis

    Reply Author

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


  • michelderock
    Posted on

    michelderock michelderock

    Reply Author

    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


  • Pete
    Posted on

    Pete Pete

    Reply Author

    I love it when code just works!

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


  • Laxmi
    Posted on

    Laxmi Laxmi

    Reply Author

    Thanks…. :)

    Regards,
    Laxmi Damani


  • alkos333
    Posted on

    alkos333 alkos333

    Reply Author

    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


  • Parker
    Posted on

    Parker Parker

    Reply Author

    Thanks for posting ~


  • Chris
    Posted on

    Chris Chris

    Reply Author

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      Thanks Chris all fixed!


  • Talakisew Binor
    Posted on

    Talakisew Binor Talakisew Binor

    Reply Author

    Very interesting, easy and valuable snippet.
    Thanks,


  • Pete
    Posted on

    Pete Pete

    Reply Author

    This worked like magic! Thank you for sharing :)


  • Jaskaran Singh Nagra
    Posted on

    Jaskaran Singh Nagra Jaskaran Singh Nagra

    Reply Author

    Correction:

    Lines 04 and 05 in first snippet must be:

    alert(first);
    alert(second);


  • CaoS
    Posted on

    CaoS CaoS

    Reply Author

    Thanks :)

    Best regards :)


  • Luka
    Posted on

    Luka Luka

    Reply Author

    Thanks. It helped me a lot!!


  • Falguni
    Posted on

    Falguni Falguni

    Reply Author

    Thanks for snippet.it is very useful and easy.


  • Vivek Shrivastava
    Posted on

    Vivek Shrivastava Vivek Shrivastava

    Reply Author

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

    Thanks


  • masterKen02
    Posted on

    masterKen02 masterKen02

    Reply Author

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


  • Ethyl Spoonamore
    Posted on

    Ethyl Spoonamore Ethyl Spoonamore

    Reply Author

    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.


  • Rush
    Posted on

    Rush Rush

    Reply Author

    You saved my day.


  • Nox
    Posted on

    Nox Nox

    Reply Author

    I love you ^^
    you made my day


  • jon mortimer
    Posted on

    jon mortimer jon mortimer

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      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


  • Chris M
    Posted on

    Chris M Chris M

    Reply Author

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


  • molokoloco
    Posted on

    molokoloco molokoloco

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @molokoloco, Thanks!


  • Peter
    Posted on

    Peter Peter

    Reply Author

    thanks for the code


  • Serdar Alten ÅžimÅŸek
    Posted on

    Serdar Alten ÅžimÅŸek Serdar Alten ÅžimÅŸek

    Reply Author

    thank you


  • stevej
    Posted on

    stevej stevej

    Reply Author

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


  • stevej
    Posted on

    stevej stevej

    Reply Author

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


  • jared
    Posted on

    jared jared

    Reply Author

    “Remember you need to include the jQuery framework.”

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

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


  • Hongpak
    Posted on

    Hongpak Hongpak

    Reply Author

    Woow! and Thanks


  • Paul Sayre
    Posted on

    Paul Sayre Paul Sayre

    Reply Author

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


  • Ledopsi
    Posted on

    Ledopsi Ledopsi

    Reply Author

    What about window.location.search ?


  • Kevin
    Posted on

    Kevin Kevin

    Reply Author

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


  • Davinder
    Posted on

    Davinder Davinder

    Reply Author

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


  • Elijah Manor
    Posted on

    Elijah Manor Elijah Manor

    Reply Author

    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


  • Balaji
    Posted on

    Balaji Balaji

    Reply Author

    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!