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 displaying 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.
<!DOCTYPE html>
<html>
<head>
<title>
How to get the fragment
identifier from a URL?
</title>
</head>
<body style =
"text-align:center;"
>
<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>
</html>
Output:
- Before clicking the button:
- After clicking the button:
- Before clicking the button:
- Approach 2: We have defined a variable hash which 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.
<!DOCTYPE html>
<html>
<head>
<title>
How to get the fragment
identifier from a URL?
</title>
</head>
<body style =
"text-align:center;"
>
<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);
alert(hash);
</script>
</body>
</html>
Output: