Parsing URL hash/fragment identifier with JavaScript

Here it is, modified from this query string parser:

function getHashParams() {

    var hashParams = {};
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&;=]+)=?([^&;]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.hash.substring(1);

    while (e = r.exec(q))
       hashParams[d(e[1])] = d(e[2]);

    return hashParams;
}

No JQuery/plug-in required

Update:

I’m now recommending the jQuery BBQ plugin as per Hovis’s answer. It covers all hash parsing issues.

Update (2019)

Apparently there is now a URLSearchParams function – see answer from @Berkant

Leave a Comment