2016-06-15 16 views
0

So habe ich das folgende Bit Code, der in gewissem Umfang funktioniert.Entfernen Sie nachstehende '/' vom Ende der 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); 
} 

Das einzige Problem ist, dass, sobald die URL der Seite geändert wird Nachladen hält, als ob ich eine Endlosschleife auf dem Gehen haben.

Irgendwelche Ideen?

Danke!

+0

Sie sollten einen Scheck, wenn Original-URL in Ordnung ist. Wenn nicht, säubern Sie es und ersetzen Sie es. Momentan stellst du immer ein. Daher unendliches Nachladen – Rajesh

Antwort

1

Sie müssen überprüfen, ob die URL tatsächlich geändert wird, und nur ihre Position ersetzen, wenn sie geändert wurde. Sie sollten wahrscheinlich auch window.url verwenden, anstatt es manuell aus dem Protokoll, dem Host und dem Pfadnamen zu erstellen.

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

die URL zu aktualisieren, ohne tatsächlich die location Aktualisierung (die in Neuladen der Browser führt), wird möglicherweise die html5 pushState Ereignis verwenden:

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