Parsing URL hash/fragment identifier with JavaScript

Yarin picture Yarin · Nov 16, 2010 · Viewed 65.9k times · Source

Looking for a way to parse key pairs out of the hash/fragment of a URL into an object/associative array with JavaScript/JQuery

Answer

Yarin picture Yarin · Nov 16, 2010

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