How to get fragmented value from a url in JavaScript

Sometimes, We want to get the fragmented value after # symbole from an url in javascript. You can check my other post on Javascript check substring exists in a String

For example, you have url as given below

using javascript, get the value contact for a given url as given below.


In HTML pages, Fragmented urls values can be used to navigate between different sections or tabs of a page.

How to get fragmented url value in javascript?

There are multiple ways we can retrieve fragmented url values

  • use window.location.hash property

window.location.hash property returns the fragmented value

if the page url is

console.log(window.location.hash); //returns  #contact value

if the page url is

console.log(window.location.hash); //returns empty value
  • using string url

if url contains a string url, use the substring() method

var strUrl = "";
var hash = strUrl.substring(strUrl.indexOf("#") + 1);
console.log(hash); // returns contact

Another way using url object

var url = new URL("");
console.log(url.hash); // returns #contact
  • using split function

Split the string using the separator(#) symbol and returns the second element from an array using index=1.

let strUrl = "";
let fragmentValue = strUrl.split("#")[1];


Learned multiple ways to find fragmented value from javascript with examples