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.
Installation
npm install path-to-regexp --save
Usage
var pathToRegexp = require('path-to-regexp')
- path A string in the express format, an array of strings, or a regular expression.
- keys An array to be populated with the keys present in the url.
- options
- sensitive When
true
the route will be case sensitive. (default: false
) - strict When
false
the trailing slash is optional. (default: false
) - end When
false
the path will match at the beginning. (default: true
)
var keys = []
var re = pathToRegexp('/foo/:bar', keys)
Parameters
The path has the ability to define parameters and automatically populate the keys array.
Named Parameters
Named parameters are defined by prefixing a colon to the parameter name (:foo
). By default, this parameter will match up to the next path segment.
var re = pathToRegexp('/:foo/:bar', keys)
re.exec('/test/route')
Suffixed Parameters
Optional
Parameters can be suffixed with a question mark (?
) to make the entire parameter optional. This will also make any prefixed path delimiter optional (/
or .
).
var re = pathToRegexp('/:foo/:bar?', keys)
re.exec('/test')
re.exec('/test/route')
Zero or more
Parameters can be suffixed with an asterisk (*
) to denote a zero or more parameter match. The prefixed path delimiter is also taken into account for the match.
var re = pathToRegexp('/:foo*', keys)
re.exec('/')
re.exec('/bar/baz')
One or more
Parameters can be suffixed with a plus sign (+
) to denote a one or more parameters match. The prefixed path delimiter is included in the match.
var re = pathToRegexp('/:foo+', keys)
re.exec('/')
re.exec('/bar/baz')
Custom Match Parameters
All parameters can be provided a custom matching regexp and override the default. Please note: Backslashes need to be escaped in strings.
var re = pathToRegexp('/:foo(\\d+)', keys)
re.exec('/123')
re.exec('/abc')
Unnamed Parameters
It is possible to write an unnamed parameter that is only a matching group. It works the same as a named parameter, except it will be numerically indexed.
var re = pathToRegexp('/:foo/(.*)', keys)
re.exec('/test/route')
Asterisk
An asterisk can be used for matching everything. It is equivalent to an unnamed matching group of (.*)
.
var re = pathToRegexp('/foo/*', keys)
re.exec('/foo/bar/baz')
Parse
The parse function is exposed via pathToRegexp.parse
. This will yield an array of strings and keys.
var tokens = pathToRegexp.parse('/route/:foo/(.*)')
console.log(tokens[0])
console.log(tokens[1])
console.log(tokens[2])
Note: This method only works with strings.
Compile ("Reverse" Path-To-RegExp)
Path-To-RegExp exposes a compile function for transforming an express path into valid path. Confusing enough? This example will straighten everything out for you.
var toPath = pathToRegexp.compile('/user/:id')
toPath({ id: 123 })
toPath({ id: 'café' })
toPath({ id: '/' })
var toPathRepeated = pathToRegexp.compile('/:segment+')
toPathRepeated({ segment: 'foo' })
toPathRepeated({ segment: ['a', 'b', 'c'] })
var toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
toPathRegexp({ id: 123 })
toPathRegexp({ id: '123' })
toPathRegexp({ id: 'abc' })
Note: The generated function will throw on any invalid input. It will execute all necessary checks to ensure the generated path is valid. This method only works with strings.
Working with Tokens
Path-To-RegExp exposes the two functions used internally that accept an array of tokens.
pathToRegexp.tokensToRegExp(tokens, options)
Transform an array of tokens into a matching regular expression.pathToRegexp.tokensToFunction(tokens)
Transform an array of tokens into a path generator function.
Compatibility with Express <= 4.x
Path-To-RegExp breaks compatibility with Express <= 4.x
:
- No longer a direct conversion to a RegExp with sugar on top - it's a path matcher with named and unnamed matching groups
- It's unlikely you previously abused this feature, it's rare and you could always use a RegExp instead
- All matching RegExp special characters can be used in a matching group. E.g.
/:user(.*)
- Other RegExp features are not support - no nested matching groups, non-capturing groups or look aheads
- Parameters have suffixes that augment meaning -
*
, +
and ?
. E.g. /:user*
Live Demo
You can see a live demo of this library in use at express-route-tester.
License
MIT