{

How to get fragmented value from a url in JavaScript


Sometimes, We want to get fragmented value after # symbole from an url in javascript

For example, you have url

abc.com/about#contact

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

contact

In html pages, Fragmented urls values can be used to navigate between different sections or tabs of an 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 fragmente value

if page url is abc.com/about#contact

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

if page url is abc.com/about

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

if url contains string url, use 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 separator(#) symbol and returns 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

THE BEST NEWSLETTER ANYWHERE
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
Subscribe
You'll get a notification every time a post gets published here.