How to remove the hash from window.location (URL) with JavaScript without page refresh?

Javascriptwindow.locationFragment Identifier

Javascript Problem Overview


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

I attempted the following solution:

window.location.hash = '';

However, this doesn't remove the hash symbol # from the URL.

Javascript Solutions


Solution 1 - Javascript

Solving this problem is much more within reach nowadays. The HTML5 History API allows us to manipulate the location bar to display any URL within the current domain.

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

Working demo: http://jsfiddle.net/AndyE/ycmPt/show/</b>

This works in Chrome 9, Firefox 4, Safari 5, Opera 11.50 and in IE 10. For unsupported browsers, you could always write a gracefully degrading script that makes use of it where available:

function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

So you can get rid of the hash symbol, just not in all browsers — yet.

Note: if you want to replace the current page in the browser history, use replaceState() instead of pushState().

Solution 2 - Javascript

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.

Solution 3 - Javascript

(Too many answers are redundant and outdated.) The best solution now is this:

history.replaceState(null, null, ' ');

Solution 4 - Javascript

Simple and elegant:

history.replaceState({}, document.title, ".");  // replace / with . to keep url

Solution 5 - Javascript

You can do it as below:

history.replaceState({}, document.title, window.location.href.split('#')[0]);

Solution 6 - Javascript

To remove the hash, you may try using this function

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

Solution 7 - Javascript

This will remove the trailing hash as well. eg: http://test.com/123#abc -> http://test.com/123

if(window.history.pushState) {
    window.history.pushState('', '/', window.location.pathname)
} else {
    window.location.hash = '';
}

Solution 8 - Javascript

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.

Solution 9 - Javascript

const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);

Solution 10 - Javascript

function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

window.addEventListener("load", function(){
    removeLocationHash();
});

Solution 11 - Javascript

<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    window.history.replaceState({}, document.title, clean_uri);
}
</script>

put this code on head section

Solution 12 - Javascript

I think, it would be more safe

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}

Solution 13 - Javascript

$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});

Solution 14 - Javascript

Try the following:

window.history.back(1);

Solution 15 - Javascript

Here is another solution to change the location using href and clear the hash without scrolling.

The magic solution is explained here. Specs here.

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

NOTE: The proposed API is now part of WhatWG HTML Living Standard

Solution 16 - Javascript

Building off one of the answers given above, use this:

var scrollV, scrollH
var loc = window.location;
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
if ("pushState" in history) {
    history.pushState("", document.title, loc.pathname + loc.search);

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;

} else {
    loc.hash = "";

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;
}

Solution 17 - Javascript

You can replace hash with null

var urlWithoutHash = document.location.href.replace(location.hash , "" );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom LehmanView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptGabriel HurleyView Answer on Stackoverflow
Solution 3 - JavascriptPacerierView Answer on Stackoverflow
Solution 4 - JavascriptcprcrackView Answer on Stackoverflow
Solution 5 - JavascriptMETALHEADView Answer on Stackoverflow
Solution 6 - JavascriptRahul GuptaView Answer on Stackoverflow
Solution 7 - JavascriptChris GunawardenaView Answer on Stackoverflow
Solution 8 - JavascriptNibras ReezaView Answer on Stackoverflow
Solution 9 - JavascriptCaseyView Answer on Stackoverflow
Solution 10 - JavascriptVimal KumarView Answer on Stackoverflow
Solution 11 - JavascriptManigandan RaamanathanView Answer on Stackoverflow
Solution 12 - JavascriptKonstantin LekhView Answer on Stackoverflow
Solution 13 - JavascriptJohnMathewView Answer on Stackoverflow
Solution 14 - JavascriptVishal SharmaView Answer on Stackoverflow
Solution 15 - JavascriptvoscausaView Answer on Stackoverflow
Solution 16 - JavascriptEngineersticityView Answer on Stackoverflow
Solution 17 - JavascriptDevang BhagdevView Answer on Stackoverflow