2016-06-15 9 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

あなたはチェックしておく必要があります

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

答えて

1

URLが実際に変更されているかどうかを確認し、変更されている場合はその場所のみを置き換える必要があります。また、おそらくwindow.urlを、プロトコル、ホスト、およびパス名から手動で構築するのではなく、使用するべきです。元の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(){ 
    window.history.pushState("object or string", "Title", url); 
} 
0

は(ブラウザをリロードになり)、実際に locationを更新せず、URLを更新するには、HTML5 pushStateイベントを使用することができます。そうでない場合は、掃除して交換してください。現在は常に設定しています。したがって、無限のリロード
関連する問題