/
PathUtils.js
59 lines (46 loc) · 1.43 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
54
55
56
57
58
59
export function addLeadingSlash(path) {
return path.charAt(0) === '/' ? path : '/' + path;
}
export function stripLeadingSlash(path) {
return path.charAt(0) === '/' ? path.substr(1) : path;
}
export function hasBasename(path, prefix) {
return (
path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 &&
'/?#'.indexOf(path.charAt(prefix.length)) !== -1
);
}
export function stripBasename(path, prefix) {
return hasBasename(path, prefix) ? path.substr(prefix.length) : path;
}
export function stripTrailingSlash(path) {
return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;
}
export function 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 function createPath(location) {
const { pathname, search, hash } = location;
let path = pathname || '/';
if (search && search !== '?')
path += search.charAt(0) === '?' ? search : `?${search}`;
if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : `#${hash}`;
return path;
}