Salva de la Puente

Pensamientos & código

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

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

Hope it helps!