Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add withFragment utility #193

Merged
merged 11 commits into from
Feb 5, 2024
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,19 @@ isEqual('/foo bar', '/foo%20bar', { encoding: true })
// false
```

### `withFragment`

Add a fragment (or hash) to a URL:

```ts
withFragment('/foo', 'bar')
// /foo#bar
withFragment('/foo#bar', 'baz')
// /foo#baz
withFragment('/foo#bar', '')
// /foo
```

## License

[MIT](./LICENSE)
Expand Down
6 changes: 6 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,9 @@ export function isEqual(a: string, b: string, options: CompareURLOptions = {}) {
}
return a === b;
}

export function withFragment(input: string, hash: string): string {
const parsed = parseURL(input);
parsed.hash = hash === "" ? "" : "#" + encodeURIComponent(hash);
pi0 marked this conversation as resolved.
Show resolved Hide resolved
return stringifyParsedURL(parsed);
}
43 changes: 43 additions & 0 deletions test/utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
withoutProtocol,
withProtocol,
isScriptProtocol,
withFragment,
} from "../src";

describe("hasProtocol", () => {
Expand Down Expand Up @@ -256,3 +257,45 @@ describe("isEqual", () => {
});
}
});

describe("withFragment", () => {
const tests = [
{
input: "https://example.com",
fragment: "foo",
out: "https://example.com#foo",
},
{
input: "https://example.com#bar",
fragment: "foo",
out: "https://example.com#foo",
},
{ input: "https://example.com", fragment: "", out: "https://example.com" },
{
input: "https://example.com#bar",
fragment: "",
out: "https://example.com",
},
{
input: "https://example.com#bar",
fragment: "0",
out: "https://example.com#0",
},
{
input: "https://example.com#bar",
fragment: "foo bar",
out: "https://example.com#foo%20bar",
},
{
input: "https://example.com?foo=bar",
fragment: "baz",
out: "https://example.com?foo=bar#baz",
},
];

for (const t of tests) {
test(`${t.input} + ${t.fragment}`, () => {
expect(withFragment(t.input, t.fragment)).toBe(t.out);
});
}
});