🤯 50% Off! 700+ courses, assessments, and books

Using Hash Urls with jQuery Example

Sam Deering

Many modern web apps these days use hash urls to add uniqueness (like a page tag, section, action etc…) to a page without refreshing it youn can identify it. This is following on from Getting Url Parameters Using jQuery to pass dynamic data to the page through through the URL. Which is still widely used on the WWW.

window.location.hash vs document.URL

Let’s take a quick look at both and below is a regex which you can use to grab the hash tag.

//using window.location.hash
$.fn.urlHash = function()
  return window.location.hash.replace('#','');

Important: location.hash is not safe for IE (including IE9). Also if your page contains an iframe then after manual refresh inside iframe content gets the old location.hash value (for first page load) while manual retrieved value is different than location.hash so it might be best to retrieve it through document.URL.

//IE Proof - URL Hash Grab - returns complete hash value
$.fn.urlHash = function()
  return document.URL.substr(document.URL.indexOf('#')+1);

So as an example to extract the dayofweek hash tag value you would do it like this:

//in context - extract dayofweek hash
//eg  url#dayofweek1 would return 1
if (document.URL.indexOf('#dayofweek'))
    week = parseInt(document.URL.substr(document.URL.indexOf('#')+1).replace('dayofweek',''))-1;

Another Decent Way

This is another decent way using a heavier regex (the pound sign is optional, since .match() never returns null).

var match = location.hash.match(/^#?(.*)$/)[1];
if (match)
   //do stuff...


var hash = location.hash.match(/#(w+)/)[1];

Issues: Returns wrong results when there is any non-latin or non-alphanumeric character in the hash. For example, for the hash #foo@o#bar$%huh hello, just “foo” would be returned. Throws a TypeError when location.hash is empty, since .match() will return null

var hash = location.hash.split('#')[1];

With the same test hash, it would at least get the “foo@o” part, which means it only fails when the hash contains a pound sign. When there’s no hash, it doesn’t throw an error, although it returns undefined instead of the empty string.

Reference Material

Get your hash — the bulletproof way