删除 URL 末尾的尾随 '/'

Remove trailing '/' from the end of URL

所以我有以下代码在一定程度上起作用。

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 是否真的被改变了,只有当它被改变时才替换它们的位置。您还应该使用 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);
    }
}

要更新 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);
}

只有在字符串末尾使用 endsWith() 才能从 url 中删除“/”。 您可以检查哈希或路径名末尾是否存在“/”并将其删除 然后重定向到末尾没有“/”的想要的页面。

您还需要跳过主页,因为它在路径名中始终是“/”

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