Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 853
Yarin Avatar asked Nov 16 '10 18:11

Yarin


People also ask

What is hash in URL JavaScript?

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 — "" .

How do I know if a URL has a hash?

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.

What is URL fragment ID?

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.

How do you find the value after an URL?

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, "" .


1 Answers

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

like image 71
Yarin Avatar answered Sep 22 '22 22:09

Yarin