joinUrl
EditJoins URL or path segments without damaging the protocol or suffix.
/** Joins URL or path segments without damaging the protocol or query string. */export const joinUrl = (base: string, ...segments: string[]): string => { if (segments.length === 0) return base; const match = base.match(/^([^?#]*)([?#].*)?$/); const basePath = match?.[1] ?? base; const suffix = match?.[2] ?? ""; const protocol = basePath.match(/^[a-z][a-z\d+.-]*:\/\//i)?.[0] ?? ""; const rest = basePath.slice(protocol.length).replace(/\/+$/, ""); const joined = [rest, ...segments] .map((segment, index) => index === 0 ? segment : segment.replace(/^\/+|\/+$/g, "")) .filter((segment, index) => index === 0 || segment.length > 0) .join("/"); return protocol + joined + suffix;};Download
Section titled “Download”wget -O src/lib/joinUrl.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/joinUrl.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/joinUrl.ts" src/lib/joinUrl.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { joinUrl } from "./joinUrl";
const endpoint = joinUrl("https://api.example.com/v1/", "/users/", "ada");// "https://api.example.com/v1/users/ada"base(string) — Absolute URL or path, optionally with query or hash....segments(string[]) — Path segments to append.- Returns a joined string with duplicate boundary slashes removed.