25

I'm trying to get the hash value after a link was clicked. Any ideas?

e.g.

The Link

index.html#needThis

This is my result:

index.htmlneedThis

How can I remove the 'index.html' ?

$('#myselector').on('click', 'a', function(){
    var hash = $(this).attr('href').replace('#', '') //get url
    console.log(hash);
})
J. Steen
  • 15,470
  • 15
  • 56
  • 63
grindking
  • 917
  • 5
  • 13
  • 29
  • Possible duplicate of http://stackoverflow.com/questions/1822598/getting-url-hash-location-and-using-it-in-jquery. You don't need to 'remove' the `index.html`, you need to grab only the hash. – Nadav S. Nov 12 '12 at 13:08
  • Why al all answers using `$(this).attr('href')`?! Use native JS where possible: `this.href` has the exact same value, withouth the need for another library or function calls. – Martijn Aug 25 '16 at 10:27

5 Answers5

71

update

Modern browsers (not sure how back it goes) can extract the hash directly from anchor elements (so i added #5)


Take your pick ..

  1. var hash = $(this).attr('href').split('#')[1];
  2. var hash = $(this).attr('href').replace(/^.*?#/,'');
  3. var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);
  4. var hash = $(this).attr('href').match(/#(.*$)/)[1];
  5. var hash = this.hash.substr(1);

update

Just revisited this and i believe that #2 can be improved to

$(this).attr('href').replace(/^.*?(#|$)/,'');

This way if no hash exists it will return empty instead of the whole url..

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
16

Just use var hash = window.location.hash.

It returns everything after #

Or if you've got a variable which contains an url:

$(this).attr('href').substring($(this).attr('href').indexOf('#'))
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
5

You can try with window location hash.

$('#myselector').on('click', 'a', function(){
    var hash = $(this).attr('href').replace('#', '') //get url
    var hash2 = window.location.hash ;
    console.log(hash2);
})
Wasim Shaikh
  • 6,880
  • 18
  • 61
  • 88
2

Why not simply use:

window.location.hash

Works just fine for me.

jucedogi
  • 46
  • 4
1

Try this,

$('#myselector').on('click', 'a', function(){
    var url = $(this).attr('href') //get url
    var arr = url.split('#');
    alert(arr[0]); //URL without hash #
    var hash = arr[1];
    console.log(hash);
})​
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70