0

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";
}
Ciprian
  • 3,066
  • 9
  • 62
  • 98

3 Answers3

5

It is a JavaScript property

 window.location.hash

Then you need to parse your string. If you use standard query string notation you can parse it with code from Parse query string in JavaScript

Community
  • 1
  • 1
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
3

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];
user3896501
  • 2,987
  • 1
  • 22
  • 25
0

There are important details overseen on the other answers:

  • FireFox returns the hash value URL encoded
  • You get the hash value, including the initial hash

To solve the Firefox problem, you need to read it this way:

var hashValue = decodeURI(window.location.hash);

which is also safe for the other browsers.

If you want to get the value without the initial has symbol #, you simply have to do this:

var hashValue = decodeURI(window.location.hash).substr(1);
JotaBe
  • 38,030
  • 8
  • 98
  • 117