Get URL parameters using jQuery

In jQuery & Javascript // // 6 Comments //

jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts.

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.example.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast

6 Comments

  • Jonny White July 18, 2013 - 2:26 pm Reply

    Thanks for this script. It was very helpful. I found that the function gave me errors when there was no parameter in the url. I made the following changes and it works well:

    $.urlParam = function(name){
    var results = new RegExp(‘[\\?&]‘ + name + ‘=([^&#]*)’).exec(window.location.href);
    if (typeof results !== “undefined” && results && 1 in results) {
    return results[1];
    }
    return 0;
    }

  • Ian August 18, 2013 - 3:26 pm Reply

    Thanks for this it was exactly what I was looking for!

  • lamps BR October 15, 2013 - 11:21 am Reply

    Great! Thank you, bro!

    But I had to change one thing when inserting this code in my page. I replaced
    return results[1] || 0;
    by
    return (results != null?results[1]:0);

    My inspector (firebug-like) was complaining about the original code.

  • Gerhard Kollinger October 28, 2013 - 10:16 am Reply

    GET-Param do not exist:
    Uncaught TypeError: Cannot read property ‘1’ of null

    Solution:
    return results != null ? results[1] : 0;

  • Sindre Sorhus November 16, 2013 - 1:31 pm Reply

    You shouldn’t use jQuery for this.

    Here’s a plain JS module:
    https://github.com/sindresorhus/query-string

Leave Comment