UNPKG

607 BPlain TextView Raw
1import { isAbsoluteUrl } from './isAbsoluteUrl'
2
3const withoutTrailingSlash = (url: string) => url.replace(/\/$/, '')
4const withoutLeadingSlash = (url: string) => url.replace(/^\//, '')
5
6export function joinUrls(
7 base: string | undefined,
8 url: string | undefined,
9): string {
10 if (!base) {
11 return url!
12 }
13 if (!url) {
14 return base
15 }
16
17 if (isAbsoluteUrl(url)) {
18 return url
19 }
20
21 const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : ''
22 base = withoutTrailingSlash(base)
23 url = withoutLeadingSlash(url)
24
25 return `${base}${delimiter}${url}`
26}