Grow your CSS skills. Land your dream job.

Last updated on:

Get Query Params as Object

Nicholas Ortenzio wrote this little plugin:

jQuery.extend({

  getQueryParameters : function(str) {
	  return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
  }

});

So if the URL is:

http://codepen.io/chriscoyier/pen/uszCr?lunch=sandwich&dinner=stirfry

You can do:

var queryParams = $.getQueryParameters();

And queryParams will be an object like:

{
   "lunch": "sandwich",
   "dinner": "stirfry"
}

Comments

  1. So very handy. Wondering if there’s a way to also provide downloadable snippets like this for easy importing into Codebox, etc.

  2. Permalink to comment#

    I cringe every time I see custom query string parsing algorithms because they’re pretty much always wrong.

    For example, ?foo=bar;foo=baz should produce:

    {
        "foo": [
            "bar",
            "baz"
        ]
    }
    

    And that code obviously can’t.

    • Ben Caplan
      Permalink to comment#

      zzzzBov, what about this as a modified alternative?

      jQuery.extend({
        getQueryParameters : function(str) {
          return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){
            return n = n.split("="),
            ( !this[n[0]] ? this[n[0]] = n[1] : ((typeof this[n[0]] === 'object') ? this[n[0]].push(n[1]) : this[n[0]]=[this[n[0]], n[1]]) ),
            this
          }.bind({}))[0];
        }
      });
      
    • Permalink to comment#

      @Ben

      This is the sort of feature where you should set up unit tests before writing. With a little bit of testing, I found that the following strings failed:

      '?=&='
      '?foo=bar&foo=baz;foo=qux'
      ''*

      * I modified the algorithm to remove || document.location.search to test strings explicitly

    • joe t
      Permalink to comment#

      @zzzzBav: If you pass that query string to PHP (assuming you’ve defined “;” as a param separator), it would produce the same as this script: last value wins the key. To produce the array you suggest, you’d need this: ?foo[]=bar;foo[]=baz. The script above would still only produce {"foo[]":"baz"}.

      It’s a narrow scope script not intended for advanced data structures. Taken in that context, it’s elegant, fast, and easy to implement.

    • joe t
      Permalink to comment#

      Sorry, meant zzzzBov. :)

    • Permalink to comment#

      @Joe t, PHP uses a completely different query string parsing standard. Use caution when parsing query strings that are used in PHP applications.

    • joe t
      Permalink to comment#

      @zzzzBov, By that logic we should beware of query strings used by any language, as there is no broadly accepted standard. Ruby, PHP, Python, .Net… Who’s right? Which one should JavaScript follow? (And why is query part of the JavaScript location object yet there’s no built-in parser?)

      Granted, expecting a JavaScript query string parser to handle all variations out there is ludicrous. Due caution should always be exercised.

      It’s an example of how it can be done, not a universal solution. Since in most cases the programmer who uses it will also control the query string itself, it obviously should be adapted to need. :-)

  3. Ben Caplan
    Permalink to comment#

    @zzzzBov I have to agree with @joe. I think the intended use case here would be “normal” query string use. What would be the use cases for the exceptions you found? I see the validity of your initial issue, in that checkboxes and multi-selects would render a query string with redundant keys, but special characters or equal signs without keys? I am interested to hear the situations you have encountered where these are useful cases.

    Also unit testing a proposed alternate script in a blog comment feed might be a bit excessive, no?

    • Permalink to comment#

      The whole reason I brought it up is to make people aware that query string parsing is not something that should be left to a crummy home-brewed solution. Edge cases aren’t an issue until you’re bitten by them.

  4. Rob
    Permalink to comment#

    This also doesn’t handle URL encoding. If a URL encoded query string is ran through this, the resulting object will still have the encoded text. Which in my experience is incorrect.

  5. Permalink to comment#

    I think there should also be a minor update to the RegEx in the replace to:

    .replace(/^.*(\?)/,'')
    

    This removes all text before the ? The original RegEx requires you to pass in

    ?param=val&param=val.
    

    The update allows you to pass in

    domain.com?param=val&param=val 

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

It's broken though, and the Jetpack team is aware of it. Your best bet right now is to escape the code yourself and post in <pre><code> tags.

If formatting screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".