pathname.utils.ts 996 B

12345678910111213141516171819202122232425262728
  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. * Extracts the pathname without query string or hash.
  7. * Use with Next.js router: getPathnameWithoutQuery(router.asPath, router.pathname)
  8. */
  9. export function getPathnameWithoutQuery(
  10. asPath: string | undefined,
  11. fallbackPathname: string
  12. ): string {
  13. if (asPath === undefined || asPath === null) return fallbackPathname
  14. const withoutQuery = asPath.split(/[?#]/)[0]
  15. return withoutQuery ?? fallbackPathname
  16. }
  17. /**
  18. * Returns the path segment at the given index, or undefined if out of bounds.
  19. * Segments are from splitting on '/', e.g. '/org/my-org/team' → ['', 'org', 'my-org', 'team']
  20. * Index 0 = '', 1 = 'org', 2 = 'my-org', 3 = 'team'
  21. */
  22. export function getPathSegment(pathname: string, index: number): string | undefined {
  23. const segments = pathname.split('/')
  24. const segment = segments[index]
  25. return segment
  26. }