From aa54b6ae8f8b320bc0e03b4ff3ffc0bb2aa2b964 Mon Sep 17 00:00:00 2001 From: Diptesh Choudhuri Date: Mon, 11 Mar 2024 17:09:17 +0530 Subject: [PATCH] feat: add `withoutHost` utility (#212) --- README.md | 11 +++++++++++ src/utils.ts | 16 ++++++++++++++++ test/utilities.test.ts | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/README.md b/README.md index c315bf56..d07900d5 100644 --- a/README.md +++ b/README.md @@ -351,6 +351,17 @@ withoutFragment("http://example.com/foo?q=123#bar") // Returns "http://example.com/foo?q=123" ``` +### `withoutHost(input)` + +Removes the host from the URL preserving everything else. + +**Example:** + +```js +withoutHost("http://example.com/foo?q=123#bar") +// Returns "/foo?q=123#bar" +``` + ### `withoutLeadingSlash(input)` Removes leading slash from the URL or pathname. diff --git a/src/utils.ts b/src/utils.ts index 0bbe92d4..a3f99779 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -576,3 +576,19 @@ export function withFragment(input: string, hash: string): string { export function withoutFragment(input: string): string { return stringifyParsedURL({ ...parseURL(input), hash: "" }); } + +/** + * Removes the host from the URL preserving everything else. + * + * @example + * ```js + * withoutHost("http://example.com/foo?q=123#bar") + * // Returns "/foo?q=123#bar" + * ``` + * + * @group utils + */ +export function withoutHost(input: string) { + const parsed = parseURL(input); + return (parsed.pathname || "/") + parsed.search + parsed.hash; +} diff --git a/test/utilities.test.ts b/test/utilities.test.ts index 78fdb26f..9da85eeb 100644 --- a/test/utilities.test.ts +++ b/test/utilities.test.ts @@ -12,6 +12,7 @@ import { isScriptProtocol, withFragment, withoutFragment, + withoutHost, } from "../src"; describe("hasProtocol", () => { @@ -332,3 +333,34 @@ describe("withoutFragment", () => { }); } }); + +describe("withoutHost", () => { + const tests = [ + { + input: "https://example.com", + out: "/", + }, + { + input: "?foo=123#hash", + out: "/?foo=123#hash", + }, + { + input: "?", + out: "/?", + }, + { + input: "https://example.com/test?foo=123#hash", + out: "/test?foo=123#hash", + }, + { + input: "http://localhost:8000/media/search/movie?query=drive", + out: "/media/search/movie?query=drive", + }, + ]; + + for (const t of tests) { + test(`${t.input}`, () => { + expect(withoutHost(t.input)).toBe(t.out); + }); + } +});