-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathparse.ts
More file actions
39 lines (31 loc) · 1.02 KB
/
parse.ts
File metadata and controls
39 lines (31 loc) · 1.02 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
import { requireNonEmptyString } from "../../lang";
import { ParsedPath } from "./types";
/**
* Returns an object from a url string.
*
* @param {string} path - The URL path string to evaluate.
* @returns {ParsedPath} An object conforming to {@link ParsedPath} type with the extracted components.
* @throws {@link EmptyStringException}
* @see {@link ParsedPath}
* @environment `Google Apps Script`, `Browser`
*/
export function parse(path: string): ParsedPath {
const result = requireNonEmptyString(path);
const reg = /^(?<dir>(?<root>\/)?(?:[^/]+\/)*)?(?<base>(?<name>[^/]+)(?<ext>\.\w+)?)?$/i;
const match = reg.exec(result);
if (!match || !match.groups) {
return {
root: undefined,
dir: undefined,
base: undefined,
name: undefined,
ext: undefined
};
}
const { root, base, name, ext } = match.groups;
let { dir } = match.groups;
if (dir && dir.endsWith("/")) {
dir = dir.slice(0, -1);
}
return { root, dir, base, name, ext } as ParsedPath;
}