JSPM

urlparams-ts

1.0.3
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q22588F
  • License MIT

Lightweight URLSearchParams interface

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

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();