javascriptjqueryurljquery-pluginsquery-string

Get query string parameters url values with jQuery / Javascript (querystring)


Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:

$('?search').val(); 

Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.

I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.


Solution

  • After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

    //Assuming URL has "?post=1234&action=edit"
    
    var urlParams = new URLSearchParams(window.location.search);
    console.log(urlParams.has('post')); // true
    console.log(urlParams.get('action')); // "edit"
    console.log(urlParams.getAll('action')); // ["edit"]
    console.log(urlParams.toString()); // "?post=1234&action=edit"
    console.log(urlParams.append('active', '1')); // "?
    
    post=1234&action=edit&active=1"
    

    UPDATE (03/21/24) : All Major Browsers Now Supported

    URLSearchParams is now supported by all major browsers

    UPDATE : IE is not supported

    use this function from an answer below instead of URLSearchParams

    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                          .exec(window.location.search);
    
        return (results !== null) ? results[1] || 0 : false;
    }
    
    console.log($.urlParam('action')); //edit