0

I have this sample html page called pound.html

<body onload="alert('loading')">
  <a href="#something">something after #</a><br />
  <a href="#">nothing after #</a><br />
  <a href="">no # at all</a><br >
</body>

I have added in an alert so that I can tell when the page reloads.

If I click on the first link, the url changes to pound.html#something as expected. If I click on the second link, it changes to pound.html#, again without reloaded. But If I click on the third link, while it puts the url back to pound.html (no #) it reloads the page.

I always see single page apps where you have no # when you start up, but once you have gone somewhere else, and then returned to the home page, you are left with #. Is there a way to make it remove the # from the url without reloading the page (like when you go back to the homepage)?


If you start on pound.html, and then click on the first link and get to pound.html#something, the browser back arrow can get you back to pound.html without reloading the page.

As mentioned in the comments, there are lots of javascript solutions here How to remove the hash from window.location (URL) with JavaScript without page refresh?

However, does anybody know if there is a way to remove to make a link do that?

Alex028502
  • 3,486
  • 2
  • 23
  • 50

1 Answers1

0

How about:

window.location.hash = '1' // add the `#1` to URL (adds hash if its not already there)
window.location.hash = '' // just leave the `#` symbol in URL
window.history.replaceState(null,document.title,location.href.slice(0, -1))

It'll remove the last character from your URL (in this case, a #)

mehulmpt
  • 15,861
  • 12
  • 48
  • 88