-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPathUtils.js
53 lines (39 loc) · 1.36 KB
/
PathUtils.js
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
export const addLeadingSlash = (path) =>
path.charAt(0) === '/' ? path : '/' + path
export const stripLeadingSlash = (path) =>
path.charAt(0) === '/' ? path.substr(1) : path
export const hasBasename = (path, prefix) =>
(new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i')).test(path)
export const stripBasename = (path, prefix) =>
hasBasename(path, prefix) ? path.substr(prefix.length) : path
export const stripTrailingSlash = (path) =>
path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path
export const parsePath = (path) => {
let pathname = path || '/'
let search = ''
let hash = ''
const hashIndex = pathname.indexOf('#')
if (hashIndex !== -1) {
hash = pathname.substr(hashIndex)
pathname = pathname.substr(0, hashIndex)
}
const searchIndex = pathname.indexOf('?')
if (searchIndex !== -1) {
search = pathname.substr(searchIndex)
pathname = pathname.substr(0, searchIndex)
}
return {
pathname,
search: search === '?' ? '' : search,
hash: hash === '#' ? '' : hash
}
}
export const createPath = (location) => {
const { rawPathname, pathname, search, hash } = location
let path = rawPathname || pathname || '/'
if (search && search !== '?')
path += (search.charAt(0) === '?' ? search : `?${search}`)
if (hash && hash !== '#')
path += (hash.charAt(0) === '#' ? hash : `#${hash}`)
return path
}