Salva de la Puente

Hacks & thoughts

URL normalization

Normalize relative URLs quickly with the Request API.

The regular way to normalize a relative path is to use the URL constructor with a second parameter. This way:

var url = new URL('/one/path/../folder', window.location.origin);
var normalized = url.href;
console.log(normalized); // https://www.salvadelapuente.com/one/folder

The second parameter is the baseURLstring and it is mandatory in the case you want to normalize a relative path. If you pass only one parameter, it must be a valid URL or you'll get an error:

var url = new URL('/one/path/../folder');
// Error: Uncaught TypeError: Failed to construct 'URL': Invalid URL
//    at <anonymous>:1:9

In my case, I usually want to normalize URLs relative to my origin and, since remembering one parameter is always better than remembering two, I ended using this pattern based on the Request constructor:

var req = new Request('/one/path/../folder');
var normalized = req.url;
console.log(normalized); // https://www.salvadelapuente.com/one/folder

Hope it helps!