Package Exports
- urlparams-ts
- urlparams-ts/lib/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (urlparams-ts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
URLSearchParams Wrapper
A lightweight TypeScript wrapper for the URLSearchParams interface, for easy compatibility with strings and Objects for search query parameters.
Usage
$ npm install urlparams-tsCreate an instance of URLParams by supplying a query string, an object with primitive values, or a URL. If no argument is provided, the constructor will use the current URL from window.location.
import { URLParams } from "urlparams-ts";
// from string
let params = new URLParams("?text=abc&bool=false");
// from object
params = new URLParams({
text: "abc",
bool: false
});
// from URL
params = new URLParams("https://github.com?text=abc&bool=false#latest");
// no parameter: use window.location
params = new URLParams();The API of URLParams is
toURLSearchParams()⇒URLSearchParamstoObject()⇒ObjecttoString()⇒stringtoCastedObject⇒Object- Object with values casted as numbers or booleans where applicable
let params = new URLParams({
text: "abc",
bool: "false",
num: "10",
nothing: undefined
});
params.toString();
// 'text=abc&bool=false&num=10'
params.toURLSearchParams();
// URLSearchParams { 'text' => 'abc', ... }
params.toObject();
// { text: 'abc', bool: 'false', num: '10' }
params.toCastedObject();
// { text: 'abc', bool: false, num: 10 }Advantages
- Parameter casting with
toCastedObject() - When supplying an Object to the constructor, all parameters with null, undefined, or an empty string as values (extraneous keys) are removed
- Reduces written code length
/// before
const params = new URLSearchParams(window.location.search);
const obj = Object.fromEntries(params);
// after
const params = new URLParams();
const obj = params.toObject();