从URL末尾删除尾随的 '/'

3

我有以下一段代码,它在某种程度上是可行的。

var url = window.location.protocol + "//" + window.location.host + window.location.pathname;

var sanitized = url
    .replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
    .replace(/\/+/g, '/')       // replace consecutive slashes with a single slash
    .replace(/\/+$/, '');       // remove trailing slashes

url = 'https://' + sanitized;

window.onload = function urlChange(){
    location.replace(url);
}

唯一的问题是,一旦URL更改,页面就像我有一个无限循环一样不断重新加载。
有任何想法吗?
谢谢!

你应该检查原始URL是否正确。如果不正确,就清理并替换它。目前你一直在设置,因此会无限重载。 - Rajesh
3个回答

2

您需要检查URL是否实际更改,仅在其已更改的情况下替换它们的位置。您还应该使用window.url而不是手动从协议、主机和路径名构建它。

var sanitized = window.url
                      .replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
                      .replace(/\/+/g, '/') // replace consecutive slashes with a single slash
                      .replace(/\/+$/, ''); // remove trailing slashes

sanitized = 'https://' + sanitized; // add https to the front

window.onload = function urlChange() {
    if (window.url !== sanitized) {
        location.replace(sanitized);
    }
}

1

若要更新URL而不实际更新location(这会导致浏览器重新加载),您可以使用html5 pushState事件:

var url = window.location.protocol + "//" + window.location.host + window.location.pathname;

var sanitized = url
    .replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
    .replace(/\/+/g, '/')       // replace consecutive slashes with a single slash
    .replace(/\/+$/, '');       // remove trailing slashes

url = 'https://' + sanitized;

window.onload = function urlChange(){
    window.history.pushState("object or string", "Title", url);
}

1

如果url结尾存在斜杠“/”,您可以使用字符串中的endsWith()方法来移除它。您可以检查hash或pathname是否以斜杠“/”结尾,然后将其移除,再重定向到所需页面。

另外,您需要跳过主页,因为它在pathname上始终为“/”。

var url_view = window.location.href;
var url_path = window.location.pathname;
var url_hash = window.location.hash;
if(url_path.endsWith("/") || url_hash.endsWith("/")) {
    //Skip Home Page
    if(url_path !== "/"){
      url_view = url_view.slice(0,-1);
      window.location.replace(url_view);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接