How to get the fragment part of a URL
By Flavio Copes
Learn how to get the fragment portion of a URL in JavaScript, the part after the # hash symbol, by reading the window.location.hash property.
To get the fragment part of the current URL in JavaScript, read the window.location.hash property. The fragment is the part of the URL after the # hash symbol.
I’ve had the need to programmatically access it. For example if the URL is index.html#second I want to know the page is pointing at second.
Here’s how I did it:
const fragment = window.location.hash
Watch out for the # character
Be careful with one detail: location.hash includes the leading #.
If the URL is index.html#second, this is what you get:
window.location.hash //'#second'
If you want just the second part, cut the first character with slice():
const fragment = window.location.hash.slice(1) //'second'
This is the pitfall I hit the first time. I compared the value to a plain string, like fragment === 'second', and the check always failed because the value was '#second'. The slice(1) call fixed it.
When the URL has no fragment at all, location.hash returns an empty string. Calling slice(1) on an empty string is safe, you still get an empty string back.
What about URLs stored in a string?
window.location only works for the URL of the current page. If you have a URL stored in a string, use the URL object instead. It exposes the same hash property:
const url = new URL('https://flaviocopes.com/axios/#installation')
url.hash //'#installation'
This works both in the browser and in Node.js.
Reacting to fragment changes
The fragment can change without a page reload. This happens when the user clicks an anchor link on the page, like a table of contents entry.
You can listen for that with the hashchange event:
window.addEventListener('hashchange', () => {
console.log(window.location.hash)
})
This is handy to highlight the current section in a sidebar, or to build very small client-side routing.
One last note. If the fragment contains encoded characters, like %20 for a space, location.hash gives you the encoded version. Pass it through decodeURIComponent() to get the readable text:
decodeURIComponent('#section%201') //'#section 1'Related posts about platform: