This repository has been archived by the owner on Sep 19, 2023. It is now read-only.
/
parseHref.ts
72 lines (62 loc) · 1.48 KB
/
parseHref.ts
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
70
71
72
const HREF_REGEX = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
/**
* ParsedHref JSON data structure
* @name ParsedHref
* @type
*/
export type ParsedHref = {
readonly href: string
readonly protocol: string
readonly host: string
readonly userInfo: string
readonly username: string
readonly password: string
readonly hostname: string
readonly port: string
readonly relative: string
readonly pathname: string
readonly directory: string
readonly file: string
readonly search: string
readonly hash: string
}
/**
* Parses an href into JSON.
* @name parseHref(href: string): ParsedHref
*/
export function parseHref(href: string): ParsedHref {
const matches = HREF_REGEX.exec(href) as RegExpExecArray
const parsedHref = {} as Record<keyof ParsedHref, string>
for (let i = 0; i < keyCount; ++i) {
const key = keys[i]
let value = matches[i] || ''
if (key === 'search' && value) {
value = '?' + value
}
if (key === 'protocol' && value && !value.endsWith(':')) {
value = value + ':'
}
if (key === 'hash') {
value = '#' + value
}
parsedHref[key] = value
}
return parsedHref
}
const keys: ReadonlyArray<keyof ParsedHref> = [
'href',
'protocol',
'host',
'userInfo',
'username',
'password',
'hostname',
'port',
'relative',
'pathname',
'directory',
'file',
'search',
'hash',
]
const keyCount = keys.length