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);
})
update
Modern browsers (not sure how back it goes) can extract the hash directly from anchor elements (so i added #5)
Take your pick ..
var hash = $(this).attr('href').split('#')[1];var hash = $(this).attr('href').replace(/^.*?#/,'');var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);var hash = $(this).attr('href').match(/#(.*$)/)[1];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..
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('#'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With