Query String to Object via regex

Just sharing a nice little code snippet that makes use of regular expressions instead of loops for converting.

function getQuery(s) {
  var query = {};

  s.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {
    if (typeof query[a] != 'undefined') {
      query[a] += ',' + d;
    } else {
      query[a] = d;
    }
  });

  return query;
}

// usage:
// var o = getQuery('maps.google.co.uk/maps?f=q&q=brighton&ie=UTF8&iwloc=addr');
// console.dir(o);

Note that if a query string key is found more than once, it’s value is appended. If you don’t want this functionality, remove the test for undefined.

4 Responses to “Query String to Object via regex”

  1. Hi Remy, very well done.
    One question, what are the ‘b’s for ? did you mean ‘\b’.
    I don’t think you even need those \b’s.

    Cheers mate

  2. @Ariel – damn escaping – they were supposed to be \b indicating a break…that said you’re right, they may not even bee required.

  3. [...] would then pass that in to my getQuery function so I had access to it as an [...]

  4. I use variant[1] that handles a few more cases like http://, unfortunately, it’s a bit heavier.

    [1]: https://gist.github.com/2588921

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight