Monday, September 23, 2024
Google search engine
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 Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments