Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing URL hash

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.)

like image 730
Randomblue Avatar asked Mar 10 '13 13:03

Randomblue


People also ask

How do you remove hash?

To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.

Why is there a hash in my URL?

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.

How do I find the URL hash?

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, "" .


1 Answers

To answer the second question (removing the # without a page refresh):

history.pushState('', document.title, window.location.pathname); 
like image 79
Randomblue Avatar answered Sep 24 '22 16:09

Randomblue