Thursday, September 4, 2025
HomeLanguagesJavascriptHow to get the fragment identifier from a URL ?

How to get the fragment identifier from a URL ?

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;">
        neveropen
    </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;">
        neveropen
    </h1>
      
    <p id="demo"></p>
      
    <script>
        var url =
            "www.neveropen.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 ?

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS