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

399,126

Solution 1

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

Solution 2

Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

http://jsfiddle.net/gilly3/sgxcL/

An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):

location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
    if (pair === "") return;
    var parts = pair.split("=");
    location.queryString[parts[0]] = parts[1] &&
        decodeURIComponent(parts[1].replace(/\+/g, " "));
});

http://jsfiddle.net/gilly3/YnCeu/

This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.

Solution 3

JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use

$.url().param('search');

This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.

Or you can use js-url instead. Its quite similar to the one below.

So you can access the query param like $.url('?search')

Solution 4

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

//URL is http://www.example.com/mypage?ref=registration&[email protected]

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //[email protected]

Use as you will.

Solution 5

This isn't my code sample, but I've used it in the past.

//First Add this to extend jQuery

    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    //Second call with this:
    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its name
    var byName = $.getUrlVar('name');
Share:
399,126

Related videos on Youtube

TroySteven
Author by

TroySteven

PHP, C#, JavaScript, Classic ASP, and ASP.NET. His database experience includes both SQL Server and MySQL.

Updated on October 09, 2021

Comments

  • TroySteven
    TroySteven over 2 years

    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.

    • Nico Westerdale
      Nico Westerdale over 12 years
    • mrtsherman
      mrtsherman over 12 years
      @NicoWesterdale - I went through that link, but didn't see any answers that solve this particular question. He said he wants exactly as above.
    • Andrew
      Andrew over 12 years
      I don't think you can do this, a string passed in gets parsed by sizzler, then resolved to an array of DOM objects. You can extend the matcher to provide custom filters, but you can't have a jquery object based on a string.
    • Quentin
      Quentin over 12 years
      Isn't $ overloaded enough?
    • Nico Westerdale
      Nico Westerdale over 12 years
      @mrtsherman Look at the getParameterByName() function in the link I provided. No you can't do it from directly within a $ prompt, but that's not what jQuery selectors are for. He's just selecting part of a URL string, not trying to access part of the DOM which is what $() does. It's a totally different thing. If you really wanted to use jQuery you could write a plugin that used this syntax: $.getParameterByName(param), there's an example further down on that page I linked to that does exactly that. Kinda pointless though.
  • Muhd
    Muhd over 12 years
    It's not common but it is valid to use semi-colons instead of ampersands in the query parameters.
  • Muhd
    Muhd over 12 years
    Nice. And the code is in the public domain so you don't even have to include the comments.
  • gilly3
    gilly3 over 12 years
    @Muhd - It's "valid" to use any delimiter you like in a querystring as long as your code understands it. But, when a form is submitted, the form fields are submitted as name=value pairs, separated by &. If your code is using a custom querystring format, obviously, you'll need to write a custom querystring parser wherever the querystring is consumed, whether on the server or the client.
  • nick
    nick almost 12 years
    The W3C recommendation is to use semi-colon delimiters, see w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.‌​2.2
  • gilly3
    gilly3 almost 12 years
    @nick - Interesting. But their suggestion for HTTP servers to treat semi-colons as ampersands only serves to make HTML prettier when using a link to mimic a form submission. It is just a suggestion and is non-standard. A standard form GET submission is encoded as application/x-www-form-urlencoded, with values separated by &. My code handles that standard. Custom url structures such as the one you linked will need a custom parser server-side and client-side. Regardless, adding such capability to my code above would be trivial.
  • nick
    nick almost 12 years
    @gilly indeed - if you want portable code you need to support both
  • mplungjan
    mplungjan over 10 years
    If your name has no junk, you can drop the first regex and it make more sense to start from location.search
  • kampsj
    kampsj over 10 years
    Good solution but won't work if you happen to be testing via file://
  • RameshVel
    RameshVel over 10 years
    Whats that have to do anything with, @kampsj
  • Jess
    Jess almost 10 years
    Hi @kampsj, testing with file:// protocol will cause a lot more stuff not to work. You can create a very quick and easy static HTML server with node.js. stackoverflow.com/questions/16333790/…
  • Kalidasan
    Kalidasan over 8 years
    Why we need plugin for very small task?
  • RameshVel
    RameshVel over 8 years
    Its based on the needs, if you are pereforming more than just retrieving a field from URL.. So if you dont want to use a plugin, then checkout the answers below, there are lot of alternatives
  • bhtabor
    bhtabor over 7 years
    Great. Thanks! I don't think you need the last closing brace tag though.
  • ClosDesign
    ClosDesign over 7 years
    Ahh yes, you are correct. Edited the post. That was left over from some if statement in my code. Thanks.
  • BrainSlugs83
    BrainSlugs83 over 7 years
    You shouldn't split on '=', it's technically okay to have a second equals sign in the value of any key/value pair. -- Only the first equals sign you encounter (per key/value pair) should be treated as a delimiter. (Also, the equals sign isn't strictly required; it's possible to have a key with no value.)
  • BrainSlugs83
    BrainSlugs83 over 7 years
    You should use window.location.search instead of .href -- otherwise, good.
  • Admin
    Admin about 7 years
    I haven't seen any erroring using this code. What browser are you using? I've tested it against current Firefox, Chrome, and Safari.
  • Jerinaw
    Jerinaw about 7 years
    Yeah sorry I read it wrong. I thought I saw it call a method on something that was returning undefined. So really it's just running once when it doesn't have to. When search is "". And you get {"": "undefined"}
  • Admin
    Admin about 7 years
    Yeah. That could probably use some refining.
  • master_dodo
    master_dodo almost 7 years
    Instead of results[1] || 0, you must do if (results) {return results[1]} return 0; bcoz query parameters may not be present at all. And modifying will handle all generic cases.
  • JanErikGunnar
    JanErikGunnar over 6 years
    This plugin is no longer maintained and the author itself is suggesting to use other plugins instead.
  • RameshVel
    RameshVel over 6 years
    thanks @JanErikGunnar, Please check the updated answer
  • Yovav
    Yovav over 6 years
    Add "i" to the RegExp() so the key can be case insensitive: new RegExp("[?&]"+key+"=([^&]+)(&|$)", "i"));
  • divine
    divine over 6 years
    is URLSearchParams supported by all browsers?
  • Saurin
    Saurin over 6 years
    Oops! ohh man, IE is not supported !! I have just tested on it. While Chrome, FF, Safari has no issue.
  • M.Babcock
    M.Babcock over 6 years
    @RameshVel Did you intend for both URI.js and js-url links to point to the same location? Maybe you meant js-url to point here?
  • RameshVel
    RameshVel over 6 years
    @M.Babcock yep the link was wrong. fixed now. thank you
  • Shane Rowatt
    Shane Rowatt about 6 years
    The return statement should be return (results && results[1]) || 0;
  • dnns
    dnns about 6 years
    If the param is not set, it'll return null, and cause an error. I modified it to: return (results !== null) ? results[1] || 0 : false; to solve the issue. This way it'll return false if the param is not set. Thanks for the solution.
  • Volomike
    Volomike about 5 years
    What do you do if you have something like https://example.com/?c=Order+ID ? That plus sign still remains on this function.
  • Volomike
    Volomike about 5 years
    This properly handled where a query param contained a plus (+) sign, while other examples did not.
  • Yogi
    Yogi about 5 years
    @divine - There is a polyfill for URLSearchParams here: github.com/WebReflection/url-search-params
  • Code-Apprentice
    Code-Apprentice about 5 years
    "Using PURE jQuery." This solution doesn't actually use any JQuery. It only extends JQuery with what could just as easily be a stand alone function.
  • Carter Medlin
    Carter Medlin almost 5 years
    To get rid of the plus sign and decode use decodeURIComponent($.urlParam('email').replace(/\+/g," "));
  • JF Gagnon
    JF Gagnon over 4 years
    Clean solution. Worked perfectly in my case.
  • Mupinc
    Mupinc about 4 years
    $.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); var k = hash.shift(); vars.push(k); vars[k] = hash.join(""); } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } });
  • Louisvdw
    Louisvdw about 4 years
    If you add a polyfill for unsupported browsers this URLSearchParams solution works well. github.com/ungap/url-search-params
  • Toskan
    Toskan almost 4 years
    wont work with say https://mytest.com/bippo/#/?utm_source=teeest or https://mytest.com/bippo/#/url/?utm_source=teeest
  • Toskan
    Toskan almost 4 years
    dont understand the jsfiddle. Will this work for example with: https://mytest.com/bippo/#/url/?utm_source=teeest
  • Toskan
    Toskan almost 4 years
    wont work with https://mytest.com/bippo/#/url/?utm_source=teeest
  • gilly3
    gilly3 over 3 years
    @Toskan - You can adapt it to work. I assume you want to treat the ?utm_source=teeest portion as the querystring. Since that portion in your URL comes after the #, it's not part of the traditional querystring, and thus not available in location.search, which both of my examples rely on. You can modify my qs function to use location.hash instead of location.search and it will work.
  • farialima
    farialima over 2 years
    The solution is not complete, il should call decodeURIComponent, and replace + with space... see previous solution