pathname.utils.ts28 lines · main
1/**
2 * Pathname utilities for safe URL/path parsing.
3 * Use these instead of direct array indexing (e.g. pathname.split('/')[3]) to avoid undefined access.
4 */
5
6/**
7 * Extracts the pathname without query string or hash.
8 * Use with Next.js router: getPathnameWithoutQuery(router.asPath, router.pathname)
9 */
10export function getPathnameWithoutQuery(
11 asPath: string | undefined,
12 fallbackPathname: string
13): string {
14 if (asPath === undefined || asPath === null) return fallbackPathname
15 const withoutQuery = asPath.split(/[?#]/)[0]
16 return withoutQuery ?? fallbackPathname
17}
18
19/**
20 * Returns the path segment at the given index, or undefined if out of bounds.
21 * Segments are from splitting on '/', e.g. '/org/my-org/team' → ['', 'org', 'my-org', 'team']
22 * Index 0 = '', 1 = 'org', 2 = 'my-org', 3 = 'team'
23 */
24export function getPathSegment(pathname: string, index: number): string | undefined {
25 const segments = pathname.split('/')
26 const segment = segments[index]
27 return segment
28}