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

42 add url utility functions #46

Merged
merged 2 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/url/get-params-from-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Returns key/value pairs of the given url with params.
* Also, check out this {@link https://github.com/steven-tey/dub/blob/main/lib/utils.ts#L330C20 | link}.
*
* @param url - the given url
* @returns key/value pairs of param and value, or an empty object
* @example
* ```ts
* const params = getParamsFromURL('https://example.org/?a=1&b=2&c=3')
* // { a: '1', b: '2', c: '3' }
* ```
*
* @public
*/
export function getParamsFromURL(url: string): Record<string, string> {
if (!url) return {};
try {
const params = new URL(url).searchParams;
const paramsObj: Record<string, string> = {};
for (const [key, value] of params.entries()) {
if (value && value !== '') {
paramsObj[key] = value;
}
}
return paramsObj;
} catch (e) {
return {};
}
}
12 changes: 12 additions & 0 deletions src/url/get-url-params.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { getParamsFromURL } from './get-params-from-url';

describe('getParamsFromURL', () => {
test.each`
input | expected
${'https://example.org/?a=1&b=2&c=3'} | ${{ a: '1', b: '2', c: '3' }}
${'https://example.org/?t=Salz+%26+Pfeffer'} | ${{ t: 'Salz & Pfeffer' }}
${'https://example.org/'} | ${{}}
`('returns $expected when input is: $input', ({ input, expected }) => {
expect(getParamsFromURL(input)).toStrictEqual(expected);
});
});