/  Technology   /  Get hash value from URL using JavaScript
Get hash value from URL using JavaScript

Get hash value from URL using JavaScript

 

Elements of a web page are sometimes changed based on the hash value (#) of the current URL. This is a very efficient method for passing a value in the URL and then loading the web page based on that value. You can easily get the value after the hash (#) from a URL using JavaScript.

Getting hash value from URL:

  • location.search���search property can also be used to set the querystring
  • search ���returns a query string including the initial question mark.
  • The window.location ���object can be written without the window prefix.
  • location ���JavaScript Browser Object Model (BOM)
  • The BOM allows JavaScript to “interact with” the browser. The object of window represents a browser window and all its corresponding features.
  • location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.

The code below was written using the split method to obtain the hash value and display it as alerts.

<!DOCTYPE html>
 <html>
 <head>
   <title>Get hash value from URL</title>
   <meta name="description" content="">
   <meta n <link rel="stylesheet" href="Goto Previous page/styles.css">
  </head>
  <body>
   <p>Get hash value from URL : Gives us alert of query params </p>
   <script>
     var url = '“https://www.youtube.com/?watch?v=j3-LV3XxhVg”'
     hash = url.split('?')[1]+ url.split('?')[2];

   if (hash) {
      alert(hash)
   } else {
      alert("No Hash Value");
   }
   </script>
 </body>
 </html>

 Output:

Get hash value from URL using JavaScript

 

 

Leave a comment