grindking
grindking

Reputation: 937

Get hash value from url

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);
})

Upvotes: 25

Views: 59895

Answers (5)

jucedogi
jucedogi

Reputation: 46

Why not simply use:

window.location.hash

Works just fine for me.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195952

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

Upvotes: 71

user1796666
user1796666

Reputation:

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('#'))

Upvotes: 16

Muthu Kumaran
Muthu Kumaran

Reputation: 17900

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);
})​

Upvotes: 1

Wasim Shaikh
Wasim Shaikh

Reputation: 7030

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);
})

Upvotes: 5

Related Questions