jqyery

How to get hash value from URL by using jQuery


In this article, you will learn about how to get hash value from URL by using jQuery.

JQuery is a speedy, lightweight, and easy-to-learn JavaScript library. With this library, you can manipulate the HTML DOM tree as well as event handling and bring interactivity to your web page. Getting a hash value from any URL is one of them. You may get a hash value by using vanilla JavaScript also. Let’s see an example of getting a hash value by using JavaScript first in the below section

let url = "https://example.com/#test/";
let hashValue = url.indexOf("#");
if (hashValue !== -1)
{
    var hash = url.substring(hashValue + 1);
    console.log(hash);
}

//Output: test

Here, we have a dummy URL and get the output by using indexOf(). Similarly, you can get the hash value by using split() and pop().

Sometimes you need to get the hash value of a current window URL. It is also similar and easy to get. Let’s see the syntax for getting the current URL hash value.

 let hash = window.location.hash;

Let’s see an example where we can set a hash value and also get the value into the alert message with the help of jQuery.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get The Hash Vaule with jQuery</title>
</head>
<body>

 <div class="section">
    <h4>Set Hash Value: </h4>
    <a id="setValue" href="#test">Set Value</a>
     
    <h4>Get Hash Value: </h4>
    <a id="getValue" href="">Get Value</a>
 </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

Here, we simply link jQuery from CDN and take two links one is for setting the hash value and another is for getting the hash value. But things won’t work at this moment, to make things work we need to add the jQuery functionality.

JQuery

$(document).ready(function () {
    $("a#getValue").click(function () {
        alert(window.location.hash.substr(1));
    });
});

Here, we simply add the functionality of jQuery to get the hash value. Let’s check the output below:

Output

URL by using jQuery

You can see that when we have clicked on the Set Value, we have got a text in our link with a hash. This text has been set by us in our HTML code. Now let’s see what happens if we click on the Get value.

URL by using jQuery

When we clicked on the Get Value an alert message comes with our value that is test. This is how you can get a hash value from URL by using jQuery.


Share on social media

//