{

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

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 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 fragmente 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]
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.