Home >Web Front-end >JS Tutorial >How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?

How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 10:57:10768browse

How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?

Removing Hash Symbols from URLs with JavaScript

Removing the hash symbol (#) from a URL without refreshing the page requires a touch more finesse than simply setting window.location.hash to an empty string.

Elegant Solution for Modern Browsers

The modern HTML5 History API offers an elegant solution:

function removeHash() {
  history.pushState("", document.title, window.location.pathname + window.location.search);
}

Example Demo:

https://jsfiddle.net/AndyE/ycmPt/

Wider Browser Support

For browsers lacking History API support, consider this gracefully degrading script:

function removeHash() {
  var scrollV = document.body.scrollTop;
  var scrollH = document.body.scrollLeft;
  var loc = window.location;

  if ("pushState" in history) {
    history.pushState("", document.title, loc.pathname + loc.search);
  } else {
    loc.hash = "";
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;
  }
}

Caveat

While this solution can remove the hash symbol, it's worth noting that it may not work in all browsers, particularly older versions.

Additional Note:

To replace the current page in the browser history, use replaceState() instead of pushState().

The above is the detailed content of How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn