Subscribe to our feed

Symfony Experts

Symfony Experts
If you have an urgent question for a symfony-related issue, this is the place to ask.


Stack Overflow

The old fashioned way


November 21, 2008 – 5:39pm Javascript get window hash/anchor, get link target

There are two functions I find myself using all the time. They are very useful for javascript events that read the link href attribute to determine an action’s target.

function getHash() {
  var hash = window.location.hash;
  return hash.substring(1); // remove #
function getLinkTarget(link) {
  return link.href.substring(link.href.indexOf('#')+1);
Posted by in  Uncategorized   |  

7 Responses to Javascript get window hash/anchor, get link target

  1. Jon Williams says:

    I’d use a regexp for the second, but those are very useful.

  2. Mani Tadayon says:

    Nice work. Sometimes I use question marks after my hash to specify actions:

    So this code is a useful extension of your function (useful to me at least!):

    function getHash(excludeQuestionMark) {
    if (typeof excludeQuestionMark == 'undefined') var excludeQuestionMark = true;
    var hash = window.location.hash;
    var stop = hash.indexOf('?');
    // if there was no question mark in the hash, or if excludeQuestionMark is set to false
    if (stop == -1 || !excludeQuestionMark)
    var returner = hash.substring(1); // remove #
    var returner = hash.substring(1,stop); // remove # and exlude everything after '?'
    return returner;

  3. Achshar says:

    hmm nice code however i was just looking for how to get the hash value so what does the second one do??

  4. Alex says:

    You can easily get the hash from a link with the `hash` property.

  5. Scott Meves says:

    WHAT?!?!? Nice. That is awesome.

  6. Anomin says:

    Thanks. This is simplified version (2 in 1):

    function getHash(link){
    if (link)
    return link.href.substring(link.href.indexOf(‘#’)+1);
    else if (window.location.hash)
    return window.location.hash.substring(1);
    return false;

  7. I prefer regex all the way, with a simple: