Open In App

How to get the fragment identifier from a URL ?

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A fragment identifier is a string of characters that refers to a resource that is inferior to a primary resource.

Approach 1: We are able to print the fragment identifier by defining a new variable as location. hash and then display it with the help of document.getElementbyId() method. 

Syntax:

var x =  location.hash;
document.getElementById("demo").innerHTML = x;

Example: In this example, we will use location.hash property. 

HTML




<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <button onclick="GFG()">
        Try it
    </button>
      
    <p id="demo"></p>
      
    <script>
        function GFG() {
            location.hash = "#fragment_identifier";
            var x = location.hash;
              
            document.getElementById(
                    "demo").innerHTML = x;
        }
    </script>
</body>


Output:

How to get the fragment identifier from a URL ?

How to get the fragment identifier from a URL ?

 

Approach 2: We have defined a variable hash that stores whatever is after the # in the URL i.e. the fragment identifier and then we display it as an alert. It is done by storing the substring in the variable. 

Syntax:

var hash = url.substring(url.indexOf('#') + 1);
alert(hash);

Example 2: This example uses substring() method to display the fragment identifier. 

HTML




<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <p id="demo"></p>
      
    <script>
        var url =
            "www.geeksforgeeks.com/article.php#hello";
          
        var hash = url.substring(url.indexOf('#') + 1);
          
        document.getElementById("demo").innerHTML = hash;
    </script>
</body>


Output: 

How to get the fragment identifier from a URL ?

How to get the fragment identifier from a URL ?



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads