JavaScript: get and set URL hash parameters?

If you want to parse a hash URL:

var hash = window.location.hash.substr(1);

var result = hash.split('&').reduce(function (res, item) {
    var parts = item.split('=');
    res[parts[0]] = parts[1];
    return res;
}, {});

That way, if you have this:
http://example.com/#from=2012-01-05&to=2013-01-01

It becomes: {'from': '2012-01-05', 'to':'2013-01-01'}

As @Dean Stamler notes in the comments, dont forget the empty starting object. }, {});

Now to set a hash URL:

window.location.hash = "from=2012-01-05&to=2013-01-01";

Leave a Comment