How to get fragmented value from a url in JavaScript

Sometimes, We want to get the fragmented value after # symbole from a 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

abc.com/about#contact

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

contact;

In HTML pages, Fragmented URL 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 abc.com/about#contact

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

if the page url is abc.com/about

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

if url contains a string url, use the substring() method with the given index value.

var strUrl = "www.abc.com/about#contact";
var hash = strUrl.substring(strUrl.indexOf("#") + 1);
console.log(hash); // returns contact
  • URL hash member Another way using url object

if a path is of type URL, hash member return fragment value

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

split function splits the string based on the separator.

  • used separator(#) symbol to split into two elements
  • returns the second element from an array using index=1.
let strUrl = "www.abc.com/about#contact";
let fragmentValue = strUrl.split("#")[1];
console.log(fragmentValue);

Conclusion

Learned multiple ways to find fragmented value from javascript with examples