ciprian ciprian - 3 months ago 12
jQuery Question

jQuery - Get url hash

I have three tabs on a page


  • Latest

  • Expired

  • Pending



When each tab is active, a hash is added to the url:

http://example.com/com/#latest

I am trying to add pagination fore each tab. So I was thinking of doing something like this:

http://example.com/com/#latest?p=5

But I don't know how to get the hash value by itself. Using
$(location).attr('hash')
returns
#latest?p=5


if( $(location).attr('hash') ) {
var tab = $(location).attr('hash');
}else{
var tab = "#latest";
}

Answer

getting hash

var hash = window.location.hash;

getting latest

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

getting page number

var num = hash.match(/p=(\d+)/)[1];