Search code examples
javascripthtmlfunctiononload

Remove trailing '/' from the end of URL


So I have the following bit of code which works to some extent.

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

The only issue is that once the url gets changed the page keeps reloading as if I have an infinite loop going on.

Any ideas?

Thanks!


Solution

  • You need to check if the url is actually changed, and only replace their location if it has been changed. You should also probably use window.url rather than manually constructing it from the protocol, host and pathname.

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