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

JavascriptJqueryAnchorFragment Identifier

Javascript Problem Overview


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

If anyone could point me in the right direction, that would be much appreciated.

Javascript Solutions


Solution 1 - Javascript

Simple use of location hash:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

Solution 2 - Javascript

  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
  }

Solution 3 - Javascript

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>

Solution 4 - Javascript

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
}

Solution 5 - Javascript

Have you tried this?

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

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

Solution 6 - Javascript

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

Solution 7 - Javascript

window.location.hash 

will return the hash identifier

Solution 8 - Javascript

...or there's a jquery selector:

$('a[href^="#"]')

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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.

Solution 16 - Javascript

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.

Solution 17 - Javascript

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.

Solution 18 - Javascript

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

  function checkHash(){
      return (location.hash ? true : false);
  }

Solution 19 - Javascript

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

Solution 20 - Javascript

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

returns -> #anchorlink

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilip MortonView Question on Stackoverflow
Solution 1 - JavascriptGarethView Answer on Stackoverflow
Solution 2 - JavascriptMark NottonView Answer on Stackoverflow
Solution 3 - JavascriptJosé LealView Answer on Stackoverflow
Solution 4 - JavascriptMarc DiethelmView Answer on Stackoverflow
Solution 5 - JavascriptJon SkeetView Answer on Stackoverflow
Solution 6 - JavascriptOral ÜNALView Answer on Stackoverflow
Solution 7 - Javascriptuser2327502View Answer on Stackoverflow
Solution 8 - JavascriptBaronVonKaneHoffenView Answer on Stackoverflow
Solution 9 - JavascriptEmmanuelView Answer on Stackoverflow
Solution 10 - Javascriptuser2465270View Answer on Stackoverflow
Solution 11 - JavascriptNicholas DavisonView Answer on Stackoverflow
Solution 12 - JavascriptGrahamView Answer on Stackoverflow
Solution 13 - JavascriptcommonpikeView Answer on Stackoverflow
Solution 14 - JavascriptBarneyView Answer on Stackoverflow
Solution 15 - JavascriptFusionView Answer on Stackoverflow
Solution 16 - JavascriptRolandoView Answer on Stackoverflow
Solution 17 - JavascriptdnnsView Answer on Stackoverflow
Solution 18 - JavascriptaabiroView Answer on Stackoverflow
Solution 19 - JavascriptUzair AshrafView Answer on Stackoverflow
Solution 20 - JavascriptmarkgView Answer on Stackoverflow