Skip to content

Commit

Permalink
Merge pull request #46 from behzadam/42-add-url-utility-functions
Browse files Browse the repository at this point in the history
42 add url utility functions
  • Loading branch information
behzadam committed Jul 12, 2023
2 parents 97e20d8 + 16615d6 commit d3f124c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
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);
});
});

0 comments on commit d3f124c

Please sign in to comment.