Parsing URL hash/fragment identifier with JavaScript

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.

To read a simple key:

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

const parsedHash = new URLSearchParams(
  window.location.hash.substring(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.


Check out: jQuery BBQ

jQuery BBQ is designed for parsing things from the url (query string or fragment), and goes a bit farther to simplify fragment-based history. This is the jQuery plugin Yarin was looking for before he put together a pure js solution. Specifically, the deparam.fragment() function does the job. Have a look!

(The support site I'm working on uses an asynchronous search, and because BBQ makes it trivial to tuck entire objects into the fragment I use it to 'persist' my search parameters. This gives my users history states for their searches, and also allows them to bookmark useful searches. Best of all, when QA finds a search defect they can link straight to the problematic results!)


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