Sunday, October 2, 2022
HomeTutorialsHow to check for a #hash in a URL using JavaScript?

How to check for a #hash in a URL using JavaScript?

-

What is #hash in a URL ?

Any URL that contains a # character is a fragment URL.A fragment is an internal page reference, sometimes called a named anchor. It usually appears at the end of a URL and begins with a hash (#) character followed by an identifier. It refers to a section within a web page.There are a few things about the fragments, the most important may be that they aren’t sent in HTTP request messages.In this article help you to check for a #hash in a URL using JavaScript.

Javascript can manipulate fragments on the current page which can be used to to add history entries for a page without forcing a complete reload.
It’s unable to read it by php. It uses by client side (browser) for hash navigation, but you can write JS code to handle hash change and send async request to your server side (php) and display result on your page.

For example:

  • http://techniblogic.com/#subscribe

Check for a #hash in a URL using JavaScript

To check whether their is a #(hash) in the URL ,we can use window.location.hash which is used to returns the anchor part of a URL, including the hash sign (#).

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

As per the above code,if their is any type of #(hash) fragment it will be return true else it will be false.

Example :

Let the URL be

  • http://techniblogic.com/#helloworld

Note: To get that extra #(hash) string without the # symbol we can use substring(1) function to skip the first character i.e. #

Javascript Code

if(window.location.hash) 
{ 
var hash = window.location.hash.substring(1);
 document.write(hash); // Fragment exists
 } 
else
 { 
document.write("No hash"); // Fragment doesn't exist 
}

Output:

helloworld

Thanking for Visiting if you like this article then Comment and Share 🙂

Techniblogic
Techniblogichttps://techniblogic.com/
Get Top Technology Reviews and Updates . Techniblogic provide you the Top Tech Reviews of Latest gadgets as well as Tech Guide.

Latest Articles

Exclusive Article

How to Find Instagram Trending Reels Song [4 Only Ways]

Looking for Instagram Trending Reels Song to create your own trending Instagram reels? Don't worry! Here are the best ways to find Instagram Trending...

LEAVE A REPLY

Please enter your comment!
Please enter your name here