What is path-to-regexp?
The path-to-regexp package is a utility for converting paths to and from regular expressions. It is commonly used for routing in web applications, allowing developers to define patterns for URL paths and extract parameters from them.
What are path-to-regexp's main functionalities?
Path to RegExp Conversion
Convert a path string into a regular expression. It can also extract named parameter keys.
const { pathToRegexp } = require('path-to-regexp');
const keys = [];
const regexp = pathToRegexp('/user/:id', keys);
Extracting Parameters from a Path
Match a path against a pattern and extract the named parameters.
const { match } = require('path-to-regexp');
const matchFn = match('/user/:id');
const result = matchFn('/user/123');
// result.params will contain the extracted parameters
Compile Path to String
Compile a path function from a string pattern, which can then be used to construct paths with parameters.
const { compile } = require('path-to-regexp');
const toPath = compile('/user/:id');
const path = toPath({ id: 123 });
// path will be '/user/123'
Other packages similar to path-to-regexp
express
Express is a web application framework for Node.js that includes its own routing capabilities, which are similar to path-to-regexp. Express uses path-to-regexp internally for its routing logic.
react-router
React Router is a routing library for React that uses path-to-regexp-like pattern matching for defining routes and extracting parameters, but it is specifically tailored for React applications.
url-pattern
url-pattern is another library for matching URLs against patterns and extracting parameters. It offers a similar API to path-to-regexp but with different syntax and additional options for pattern matching.
Path-to-RegExp
Turn an Express-style path string such as /user/:name
into a regular expression.
Note: This is a legacy branch. You should upgrade to 1.x
.
Usage
var pathToRegexp = require('path-to-regexp');
pathToRegexp(path, keys, options)
- path A string in the express format, an array of such strings, or a regular expression
- keys An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings.
- options
- options.sensitive Defaults to false, set this to true to make routes case sensitive
- options.strict Defaults to false, set this to true to make the trailing slash matter.
- options.end Defaults to true, set this to false to only match the prefix of the URL.
var keys = [];
var exp = pathToRegexp('/foo/:bar', keys);
Live Demo
You can see a live demo of this library in use at express-route-tester.
License
MIT