How can you check for a #hash in a URL using JavaScript?
Asked Answered
H

20

921

I have some jQuery/JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}
Hyperbole answered 18/11, 2008 at 11:35 Comment(0)
I
1635

Simple use of location hash:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
Isoagglutinin answered 18/11, 2008 at 11:37 Comment(4)
Additional: the .location object is only available on the current window's URL, you can't do this for an arbitrary URL (e.g. one stored in a string variable)Isoagglutinin
Also, location properties like .hash and .query are also available on <a> elementsIsoagglutinin
.search is available on an <a>, not .query. Sample jQuery: $("<a/>").attr({ "href": "http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest" })[0]. .hash => "#fragmenttest" and .search = ?qs=1. From there, hit up the querystring extraction question to get something other than a string.Helgeson
Please note that window.location.hash is empty if url ends with '#'. It is ok if you are looking for hash, but not if you are checking if the current URL contains a #.Phyliciaphylis
L
391
  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }
Loferski answered 13/7, 2011 at 16:46 Comment(0)
I
58

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
Incapacious answered 18/11, 2008 at 11:41 Comment(0)
V
45

If the URI is not the document's location this snippet will do what you want.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}
Viens answered 8/3, 2012 at 10:42 Comment(0)
P
30

Have you tried this?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}

(Where url is the URL you want to check, obviously.)

Politesse answered 18/11, 2008 at 11:37 Comment(0)
K
19
$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

This will solve the problem ;)

Keelin answered 31/8, 2011 at 13:44 Comment(0)
S
17
window.location.hash 

will return the hash identifier

Sand answered 27/4, 2013 at 18:31 Comment(0)
E
10

...or there's a jquery selector:

$('a[href^="#"]')
Edla answered 19/4, 2012 at 13:18 Comment(0)
P
7

You can parse urls using modern JS:

var my_url = new URL('http://www.google.sk/foo?boo=123#baz');

my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
​my_url.protocol; // "http:"
​my_url.search; // outputs "?doo=123"

urls with no hash will return empty string.

Pulchia answered 13/10, 2020 at 11:32 Comment(0)
T
6

Here's what you can do to periodically check for a change of hash, and then call a function to process the hash value.

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}
Tengdin answered 5/7, 2010 at 22:23 Comment(1)
thats only nessesary in ie 6 + 7. Al other browsers have included the onhashchange eventMargeret
S
5
function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}
Sentimental answered 7/6, 2013 at 23:58 Comment(0)
D
5

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});
Disadvantage answered 5/9, 2013 at 17:32 Comment(0)
A
4
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
Accusal answered 6/7, 2013 at 10:37 Comment(0)
C
3

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

Contemplate answered 20/2, 2012 at 22:42 Comment(0)
C
3

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

var a = document.createElement('a');
a.href = string;

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

Closeknit answered 10/9, 2013 at 13:58 Comment(0)
I
1

Usually clicks go first than location changes, so after a click is a good idea to setTimeOut to get updated window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

or you can listen location with:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

I wrote a jQuery plugin that does something like what you want to do.

It's a simple anchor router.

Indisposed answered 20/6, 2012 at 18:18 Comment(0)
S
1

Here is a simple function that returns true or false (has / doesn't have a hashtag):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

Returns true in this case.

Based on @jon-skeet's comment.

Spiros answered 29/11, 2015 at 11:22 Comment(0)
L
1

This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }
Live answered 18/7, 2018 at 9:31 Comment(0)
G
1

I noticed that all of these answers mostly check window.location.hash and make it difficult to write tests.

 const hasHash = string => string.includes('#')

You can also remove the hash from a url like so:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}

And finally you can combine the logic together:

if(hasHash(url)) {
 url = removeHash(url)
}
Geminate answered 15/4, 2021 at 1:17 Comment(0)
V
-2

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink
Varini answered 27/10, 2014 at 8:45 Comment(2)
Not possible as hash is appended after the query string and is never sent to server. The only time hash would appear before query string is when you modified the url by hand.Herring
yep, but sometimes people send urls on this format. this is just so you can get only the hash value and neglect the others. :)Varini

© 2022 - 2024 — McMap. All rights reserved.