How to remove the hash from [removed] (URL) with JavaScript without page refresh?

前端 未结 16 3066
无人及你
无人及你 2020-11-22 02:53

I have URL like: http://example.com#something, how do I remove #something, without causing the page to refresh?

I attempted the following

相关标签:
16条回答
  • 2020-11-22 03:13

    Initial question:

    window.location.href.substr(0, window.location.href.indexOf('#'))
    

    or

    window.location.href.split('#')[0]
    

    both will return the URL without the hash or anything after it.

    With regards to your edit:

    Any change to window.location will trigger a page refresh. You can change window.location.hash without triggering the refresh (though the window will jump if your hash matches an id on the page), but you can't get rid of the hash sign. Take your pick for which is worse...

    MOST UP-TO-DATE ANSWER

    The right answer on how to do it without sacrificing (either full reload or leaving the hash sign there) is down here. Leaving this answer here though with respect to being the original one in 2009 whereas the correct one which leverages new browser APIs was given 1.5 years later.

    0 讨论(0)
  • 2020-11-22 03:16

    You can do it as below:

    history.replaceState({}, document.title, window.location.href.split('#')[0]);
    
    0 讨论(0)
  • 2020-11-22 03:16

    How about the following?

    window.location.hash=' '

    Please note that am setting the hash to a single space and not an empty string.


    Setting the hash to an invalid anchor does not cause a refresh either. Such as,

    window.location.hash='invalidtag'

    But, I find above solution to be misleading. This seems to indicate that there is an anchor on the given position with the given name although there isn't one. At the same time, using an empty string causes page to move to the top which can be unacceptable at times. Using a space also ensures that whenever the URL is copied and bookmarked and visited again, the page will usually be at the top and the space will be ignored.

    And, hey, this is my first answer on StackOverflow. Hope someone finds it useful and it matches the community standards.

    0 讨论(0)
  • 2020-11-22 03:24

    Try the following:

    window.history.back(1);
    
    0 讨论(0)
提交回复
热议问题