2016-06-15 134 views
0

所以我有以下一些代码在某种程度上起作用。从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被更改,页面不断重新加载,就好像我有一个无限循环继续。

任何想法?

谢谢!

+0

你应该有一个检查,如果原始URL是好的。如果没有,请清洁并更换。目前你一直在设置。因此无限重新加载 – Rajesh

回答

1

您需要检查网址是否实际发生了更改,并且只有在发生更改时才更换它们的位置。您也应该使用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); 
    } 
} 
0

要更新而不实际更新location的URL(这会导致重新加载浏览器),你可以使用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); 
}