Looking for a way to parse key pairs out of the hash/fragment of a URL into an object/associative array with JavaScript/JQuery
The hash property of the URL interface is a string containing a '#' followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string — "" .
The task is to check whether an URL contains or not. This can be done by using the Location hash property in JavaScript. It returns the string which represents the anchor part of a URL including the hash '#' sign.
The fragment identifier introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document. The generic syntax is specified in RFC 3986. The hash-mark separator in URIs is not part of the fragment identifier.
Get hash value for the current URL Alternatively, if you need a hash value for the current window URL, you can just use window. location. hash , which returns a string containing a '#' , followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this returns an empty string, "" .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With