normalize-url.js
953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"use strict";
/* eslint-disable */
/**
* @param {string[]} pathComponents
* @returns {string}
*/
function normalizeUrl(pathComponents) {
return pathComponents.reduce(function (accumulator, item) {
switch (item) {
case "..":
accumulator.pop();
break;
case ".":
break;
default:
accumulator.push(item);
}
return accumulator;
}, /** @type {string[]} */[]).join("/");
}
/**
* @param {string} urlString
* @returns {string}
*/
module.exports = function (urlString) {
urlString = urlString.trim();
if (/^data:/i.test(urlString)) {
return urlString;
}
var protocol = urlString.indexOf("//") !== -1 ? urlString.split("//")[0] + "//" : "";
var components = urlString.replace(new RegExp(protocol, "i"), "").split("/");
var host = components[0].toLowerCase().replace(/\.$/, "");
components[0] = "";
var path = normalizeUrl(components);
return protocol + host + path;
};