Parsing query string in javascript

Well there are hell lot of solution out there for parsing query strings in javascript, but still /me managed to make my own function!

params = (function () {
 
    res = {};
 
    window.location.search.replace("?","").split('&').map(
 
    function (q) {
        var v = q.split('=');
        res[v[0]] = v[1];
    });
 
    return res;
})();

Let's break it down!

The above code is an immediate function invokation that results a result object, which is stored in params.

We may pass params to a javascript like http://example.com/show.js?query_string

Where the query_string is a key, value pair like : field1=value1&field2=value2&field3=value3...

For better understanding, consider an example where the window.location is something like below :

http://www.example.com/post.php?foo=bar&hello=world

Now, window.location.search.replace("?","").split('&') will result an array like ["foo=bar", "hello=world"] i.e after filtering "?" and splitting over "&"

The resultant array is applied with a function which splits each element of an array with '=' and the key, value pair is populated to the result object and then finally the result object is returned, which gets assigned to params object.

JSON.stringify(params)
"{"foo":"bar","hello":"world"}"
 
params['foo']
'bar'
 
params['hello']
'world'

Update 0 MDN

// Simple regular expression to match http / https / ftp-style URLs.
var parsedURL = /^(\w+):\/\/([^\/]+)\/(.*)$/.exec(url);
if (!parsedURL)
  return null;
var [, protocol, fullhost, fullpath] = parsedURL;

Share this