Parsing URL hash/fragment identifier with JavaScript

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


Solution 1:

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

Solution 2:

Use URLSearchParams. Browser coverage: https://caniuse.com/urlsearchparams. It's fully supported in major browsers. Here is a polyfill if you need to use this on unsupported browsers.

How to read a simple key:

// window.location.hash = "#any_hash_key=any_value"

const parsedHash = new URLSearchParams(
  window.location.hash.substr(1) // skip the first char (#)
);

console.log(parsedHash.get("any_hash_key")); // any_value

Check out the Mozilla docs I linked above to see all of the methods of the interface.