简体   繁体   中英

Completely remove hash from URL

I was wondering how to take away the id from the url. Like so:

Link to page:

http://www.exampledomain.com/index.html#example

When user click the link it becomes:

http://www.exampledomain.com/index.html

There are several approaches to this, depending on your specific context.

If you just want to remove the hash value:

    location.hash = '';

...but this leaves the # in the location. (It also scrolls the user to the top of the page.) To remove that:

    location = location.pathname;

...but this will reload the page, too. To solve all these problems:

    history.pushState({},'',location.pathname); 
    // back button returns to #example

or

    history.replaceState({},'',location.pathname); 
    // back button doesn't return to #example

...which isn't supported in some old browsers (including IE 9), but those are vanishing rapidly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM