How to read and change URL hash with JavaScript

January 24, 2021

You can read the current URL hash (the part of the URL after #) like this:

const hash = location.hash
console.log(hash)

And change it like this:

location.hash = "foo"

You can detect whenever the hash changes like this:

window.addEventListener("hashchange", event => {
  console.log("hash changed", event)
})

A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Please use this form to let me know or ask for help!