Visit stackoverflow.com/#_=_
and window.location.hash
evaluates to #_=_
. Fine.
Now execute window.location.hash = ''
to clear the hash, and the URL becomes stackoverflow.com/#
. (Notice the trailing #
.)
Why is the #
in window.location.hash
inconsistently included or excluded? How can the #
be removed from the URL without reloading the page?
(MDN says
[the hash is] the part of the URL that follows the # symbol, including the # symbol.
but that is not true for in the case of an empty hash.)
To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.
A hash sign (#) in a URL is referred to as a fragment. Historically, URL fragments have been used to automatically set the browser's scroll position to a predefined location in the web page. In that sense, if a URL refers to a document, then the fragment refers to a specific subsection of that document.
Get hash value for the current URL Alternatively, if you need a hash value for the current window URL, you can just use window. location. hash , which returns a string containing a '#' , followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this returns an empty string, "" .
To answer the second question (removing the #
without a page refresh):
history.pushState('', document.title, window.location.pathname);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With