Path to/from params
Convert a path, e.g. places/france/paris/
, that matches a pattern with Express-style placeholders, e.g. 'places/:country/:city'
to/from an array of parameters, e.g. {country:'france',city:'paris'}
A a friendlier/easier wrapper for path-to-regexp. Built regexes are internally cached for performance and everything is fully unit tested with Jest.
Installation
npm install path-to-from-params
Usage
Get parameters from a path string
const pathToParams = ;const params = ;console; // {country:'france',city:'paris'}
Build a path string from parameters
const pathFromParams = ;const path = ;console; // 'places/france/paris'
Get parameters from a path string (with optional parameters)
const pathToParams = ;const params = ;console; // {country:'france',city:undefined}
Build a path string from parameters (with optional parameters)
const pathFromParams = ;const path = ;console; // 'places/brazil'
API
pathToParams()
Convert a path to a plain object of parameters. Returns an array any parameters named in the pattern that were found in the path, e.g. {country:'china',city:'shanghai'}
-
pattern
(string)
The pattern for the path, e.g.'places/:country/:city?'
-
path
(string)
The path itself, e.g.'places/china/shanghai'
pathFromParams()
Build a path from a pattern and an array of parameters. Returns the path string that was built, e.g. 'places/china/shanghai'
-
pattern
(string)
The pattern for the path, e.g.'places/:country/:city?'
-
params
(object)
The object containing the parameters, e.g.{country:'china',city:'shanghai'}