forked from withastro/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
38 lines (31 loc) · 1.38 KB
/
util.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
import type { CollectionEntry } from 'astro:content';
export function getLanguageFromURL(pathname: string) {
const langCodeMatch = pathname.match(/\/([a-z]{2}-?[a-z]{0,2})\//);
return langCodeMatch ? langCodeMatch[1] : 'en';
}
/** Remove \ and / from beginning of string */
export function removeLeadingSlash(path: string) {
return path.replace(/^[/\\]+/, '');
}
/** Remove \ and / from end of string */
export function removeTrailingSlash(path: string) {
return path.replace(/[/\\]+$/, '');
}
/** Get a page’s slug, without the language prefix (e.g. `'en/migrate'` => `'migrate'`). */
export const stripLangFromSlug = (slug: CollectionEntry<'docs'>['slug']) =>
slug.split('/').slice(1).join('/');
/** Get a page’s lang tag from its slug (e.g. `'en/migrate'` => `'en'`). */
export const getLangFromSlug = (slug: CollectionEntry<'docs'>['slug']) => slug.split('/')[0];
/** Remove the subpage segment of a URL string */
export function removeSubpageSegment(path: string) {
// Include new pages with subpages as part of this regex.
const regex = /(?:install|deploy|integrations-guide|tutorial|migrate-to-astro|cms)\//;
const matches = regex.exec(path);
if (matches) {
const matchIndex = matches.index;
// Get the first slash index after the main page path segment.
const slashIndex = path.slice(matchIndex).indexOf('/') + matchIndex;
return path.slice(0, slashIndex);
}
return path;
}