如何使用 JavaScript 从 window.location (URL) 中删除哈希而不刷新页面?

发布于 2024-08-04 09:39:03 字数 232 浏览 12 评论 0原文

我的 URL 如下:http://example.com#something,如何删除 #something,而不导致页面刷新?

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从 URL 中删除哈希符号 #

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

笨笨の傻瓜 2024-08-11 09:39:04

这也将删除尾随哈希。
例如: http://test.com/123#abc -> http://test.com/123

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

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 = '';
}
若水微香 2024-08-11 09:39:04

要删除哈希,您可以尝试使用此函数

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);
    }
}

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);
    }
}
傾城如夢未必闌珊 2024-08-11 09:39:04

下面的怎么样?

window.location.hash=' '

请注意,我将哈希设置为单个空格而不是空字符串。


将哈希设置为无效锚点也不会导致刷新。例如,

window.location.hash='invalidtag'

但是,我发现上述解决方案具有误导性。这似乎表明在给定位置上有一个具有给定名称的锚点,尽管实际上没有。同时,使用空字符串会导致页面移动到顶部,这有时是不可接受的。使用空格还可以确保每当复制 URL、添加书签并再次访问该 URL 时,该页面通常会位于顶部并且空格将被忽略。

而且,嘿,这是我在 StackOverflow 上的第一个回答。希望有人觉得它有用并且符合社区标准。

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.

北风几吹夏 2024-08-11 09:39:04
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
晚雾 2024-08-11 09:39:04
function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

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

window.addEventListener("load", function(){
    removeLocationHash();
});
小忆控 2024-08-11 09:39:04
<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>

将此代码放在头部

<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

药祭#氼 2024-08-11 09:39:04

我想,这样会更安全

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

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 = '';
}
汹涌人海 2024-08-11 09:39:04
if (window.location.href.includes('#')) {
    const cleanedUrl = window.location.href.split('#')[0];
    window.history.replaceState(null, null, cleanedUrl);
}
if (window.location.href.includes('#')) {
    const cleanedUrl = window.location.href.split('#')[0];
    window.history.replaceState(null, null, cleanedUrl);
}
油饼 2024-08-11 09:39:04

请尝试以下操作:

window.history.back(1);

Try the following:

window.history.back(1);
oО清风挽发oО 2024-08-11 09:39:04

这是使用 href 更改位置并清除散列而不滚动的另一种解决方案。

此处解释了神奇的解决方案。规格此处

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

注意:提议的 API 现在是 WhatWG HTML Living Standard 的一部分

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

平定天下 2024-08-11 09:39:04
$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});
$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});
回忆凄美了谁 2024-08-11 09:39:04

根据上面给出的答案之一,使用:

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;
}

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;
}
失去的东西太少 2024-08-11 09:39:04

您可以将 hash 替换为 null

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

You can replace hash with null

var urlWithoutHash = document.location.href.replace(location.hash , "" );
离旧人 2024-08-11 09:39:03

如今解决这个问题更加触手可及。 HTML5 History API 允许我们操作地址栏以显示其中的任何 URL当前域。

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

工作演示:http://jsfiddle.net/AndyE/ycmPt/show/

这个适用于 Chrome 9、Firefox 4、Safari 5、Opera 11.50 IE 10。对于不受支持的浏览器,您始终可以编写一个优雅的降级脚本,在可用的情况下使用它:

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;
    }
}

这样您就可以摆脱哈希符号,只是还没有在所有浏览器中出现。

注意:如果要替换浏览器历史记录中的当前页面,请使用 replaceState() 而不是 pushState()

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/

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().

や三分注定 2024-08-11 09:39:03

初始问题:

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

或者

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

两者都会返回不带哈希值或后面任何内容的 URL。

关于您的编辑:

window.location 的任何更改都将触发页面刷新。您可以更改 window.location.hash 而不触发刷新(尽管如果您的哈希与页面上的 ID 匹配,窗口将会跳转),但您无法摆脱哈希符号。选择哪个更糟糕...

最新答案

关于如何在不做出牺牲(完全重新加载或将哈希符号留在那里)的情况下做到这一点的正确答案是在这里。尽管将这个答案留在这里,但它是 2009 年的原始答案,而利用新浏览器 API 的正确答案是在 1.5 年后给出的。

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 up 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.

治碍 2024-08-11 09:39:03

(太多的答案都是多余且过时的。)现在最好的解决方案是这样的:

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

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

history.replaceState(null, null, ' ');
染墨丶若流云 2024-08-11 09:39:03

简洁优雅:

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

Simple and elegant:

history.replaceState({}, document.title, ".");  // replace / with . to keep url
鹿童谣 2024-08-11 09:39:03

您可以按如下方式进行:

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

You can do it as below:

history.replaceState({}, document.title, window.location.href.split('#')[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文