-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.ts
More file actions
69 lines (55 loc) · 2.03 KB
/
url.ts
File metadata and controls
69 lines (55 loc) · 2.03 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const protocolRegex = /^[^/:]+:\/*$/;
const fileProtocolRegex = /^file:\/\/\//;
function normalize(strArray: string[]) {
const resultArray = [];
if (strArray.length === 0) {
return "";
}
if (typeof strArray[0] !== "string") {
throw new TypeError("Url must be a string. Received " + strArray[0]);
}
// If the first part is a plain protocol, we combine it with the next part.
const match = protocolRegex.exec(strArray[0]);
if (match && strArray.length > 1) {
const first = strArray.shift();
strArray[0] = first + strArray[0];
}
// There must be two or three slashes in the file protocol, two slashes in anything else.
if (fileProtocolRegex.exec(strArray[0])) {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1:///");
} else {
strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1://");
}
for (let i = 0; i < strArray.length; i++) {
let component = strArray[i];
if (typeof component !== "string") {
throw new TypeError("Url must be a string. Received " + component);
}
if (component === "") {
continue;
}
if (i > 0) {
// Removing the starting slashes for each component but the first.
component = component.replace(/^\/+/, "");
}
if (i < strArray.length - 1) {
// Removing the ending slashes for each component but the last.
component = component.replace(/\/+$/, "");
} else {
// For the last component we will combine multiple slashes to a single one.
component = component.replace(/\/+$/, "/");
}
resultArray.push(component);
}
let str = resultArray.join("/");
// Each input component is now separated by a single slash except the possible first plain protocol part.
// remove trailing slash before parameters or hash
str = str.replace(/\/(\?|&|#[^!])/g, "$1");
// replace ? in parameters with &
const parts = str.split("?");
str = parts.shift() + (parts.length > 0 ? "?" : "") + parts.join("&");
return str;
}
export function join(...args: (string | string[])[]) {
return normalize(args.flat());
}