Skip to content

Commit bcaccdc

Browse files
committed
feat: add new funciton
1 parent ea4295e commit bcaccdc

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/parseUrl.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { ParsedURL } from './types'
2+
const PROTOCOL_REGEX = /^\w+:(\/\/)?/
3+
const PROTOCOL_RELATIVE_REGEX = /^\/\/[^/]+/
4+
5+
export function hasProtocol(inputStr: string, acceptProtocolRelative = false): boolean {
6+
return PROTOCOL_REGEX.test(inputStr) || (acceptProtocolRelative && PROTOCOL_RELATIVE_REGEX.test(inputStr))
7+
}
8+
9+
export function parseURL(input = '', defaultProto?: string): ParsedURL {
10+
if (!hasProtocol(input, true))
11+
return defaultProto ? parseURL(defaultProto + input) : parsePath(input)
12+
13+
const [protocol = '', auth, hostAndPath = ''] = (input.replace(/\\/g, '/').match(/([^:/]+:)?\/\/([^/@]+@)?(.*)/) || []).splice(1)
14+
const [host = '', path = ''] = (hostAndPath.match(/([^/?#]*)(.*)?/) || []).splice(1)
15+
const { pathname, search, hash } = parsePath(path)
16+
17+
return {
18+
protocol,
19+
auth: auth ? auth.substr(0, auth.length - 1) : '',
20+
host,
21+
pathname,
22+
search,
23+
hash,
24+
}
25+
}
26+
27+
export function parsePath(input = ''): ParsedURL {
28+
const [pathname = '', search = '', hash = ''] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1)
29+
30+
return {
31+
pathname,
32+
search,
33+
hash,
34+
}
35+
}
36+

src/types.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,12 @@ export interface MutationObserverInit {
140140
characterDataOldValue?: boolean
141141
attributeFilter?: string[]
142142
}
143+
144+
export interface ParsedURL {
145+
protocol?: string
146+
host?: string
147+
auth?: string
148+
pathname: string
149+
hash: string
150+
search: string
151+
}

0 commit comments

Comments
 (0)