How to get fragmented value from a url in JavaScript

How to get fragmented value  from a url in JavaScript example

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 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

var strUrl = "www.abc.com/about#contact";
var hash = strUrl.substring(strUrl.indexOf('#')+1);
console.log(hash); // returns contact

Another way using url object

var url = new URL('https://abc.com/about#contact');
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 = "www.abc.com/about#contact";
let fragmentValue=strUrl.split('#')[1]


Learned multiple ways to find fragmented value from javascript with examples

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.