Skip to content

Commit

Permalink
feat: add withFragment utility (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnisDa authored Feb 5, 2024
1 parent 7a4148c commit c39b9e9
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
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 === "" ? "" : "#" + encodeURI(hash);
return stringifyParsedURL(parsed);
}
48 changes: 48 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 @@ -257,3 +258,50 @@ 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#bar",
fragment: "foo/bar",
out: "https://example.com#foo/bar",
},
{
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);
});
}
});

0 comments on commit c39b9e9

Please sign in to comment.