2016-06-15 167 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); 
}