Skip to content

Instantly share code, notes, and snippets.

@sagrawal31
Last active December 27, 2019 10:30
Show Gist options
  • Save sagrawal31/511baa64e512f284a0775895a6a62849 to your computer and use it in GitHub Desktop.
Save sagrawal31/511baa64e512f284a0775895a6a62849 to your computer and use it in GitHub Desktop.
A simple wrapper in TypeScript to easily parse & handle the URL
const url = new URLWrapper('https://example.com/?foo=bar&name=undefined&age=3');
console.log(url.getParam('foo') === 'bar');
console.log(url.getParam('name') === undefined);
console.log(url.getParam('age') === '3');
/**
* A wrapper around browser's URL for some utility params.
*
* @author Shashank Agrawal
*/
export class URLWrapper {
private readonly _url: URL;
private readonly _params: URLSearchParams;
constructor(rawURL: string) {
try {
this._url = new URL(rawURL);
this._params = new URLSearchParams(this._url.search);
} catch (e) {
console.error('Un-parsable URL', e);
}
}
/**
* Method to get the value from the search params. Also handle any string of 'undefined' or 'null'.
* @param name The parameter name to get the value
* @return The parameter value. Return empty string if not available.
*/
getParam(name: string): string | undefined {
if (!this._params) {
return '';
}
const value = this._params.get(name);
return (!value || value === 'undefined' || value === 'null') ? undefined : value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment