1.0.3 • Published 1 year ago

urlparams-ts v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

URLSearchParams Wrapper

License Version Downloads Size

A lightweight TypeScript wrapper for the URLSearchParams interface, for easy compatibility with strings and Objects for search query parameters.

Usage

$ npm install urlparams-ts

Create 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()URLSearchParams
  • toObject()Object
  • toString()string
  • toCastedObjectObject
    • 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();
1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago