Skip to content

Commit

Permalink
feat: add withoutHost utility (#212)
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnisDa authored Mar 11, 2024
1 parent 595f7bb commit aa54b6a
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
32 changes: 32 additions & 0 deletions test/utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isScriptProtocol,
withFragment,
withoutFragment,
withoutHost,
} from "../src";

describe("hasProtocol", () => {
Expand Down Expand Up @@ -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);
});
}
});

0 comments on commit aa54b6a

Please sign in to comment.