Path-to-RegExp
Turn a path string such as /user/:name
into a regular expression.
URLPattern version with lenient support
This is a fork of Path-to-RegExp with additional lenient mode support in the lexer, which is required for URLPattern.
Installation
npm install path-to-regexp --save
Usage
const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
- path A string, array of strings, or a regular expression.
- keys An array to populate with keys found in the path.
- options
- sensitive When
true
the regexp will be case sensitive. (default: false
) - strict When
true
the regexp won't allow an optional trailing delimiter to match. (default: false
) - end When
true
the regexp will match to the end of the string. (default: true
) - start When
true
the regexp will match from the beginning of the string. (default: true
) - delimiter The default delimiter for segments, e.g.
[^/#?]
for :named
patterns. (default: '/#?'
) - endsWith Optional character, or list of characters, to treat as "end" characters.
- encode A function to encode strings before inserting into
RegExp
. (default: x => x
) - prefixes List of characters to automatically consider prefixes when parsing. (default:
./
)
const keys = [];
const regexp = pathToRegexp("/foo/:bar", keys);
Please note: The RegExp
returned by path-to-regexp
is intended for ordered data (e.g. pathnames, hostnames). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc). When using paths that contain query strings, you need to escape the question mark (?
) to ensure it does not flag the parameter as optional.
Parameters
The path argument is used to define parameters and populate keys.
Named Parameters
Named parameters are defined by prefixing a colon to the parameter name (:foo
).
const regexp = pathToRegexp("/:foo/:bar");
regexp.exec("/test/route");
Please note: Parameter names must use "word characters" ([A-Za-z0-9_]
).
Custom Matching Parameters
Parameters can have a custom regexp, which overrides the default match ([^/]+
). For example, you can match digits or names in a path:
const regexpNumbers = pathToRegexp("/icon-:foo(\\d+).png");
regexpNumbers.exec("/icon-123.png");
regexpNumbers.exec("/icon-abc.png");
const regexpWord = pathToRegexp("/(user|u)");
regexpWord.exec("/u");
regexpWord.exec("/users");
Tip: Backslashes need to be escaped with another backslash in JavaScript strings.
Custom Prefix and Suffix
Parameters can be wrapped in {}
to create custom prefixes or suffixes for your segment:
const regexp = pathToRegexp("/:attr1?{-:attr2}?{-:attr3}?");
regexp.exec("/test");
regexp.exec("/test-test");
Unnamed Parameters
It is possible to write an unnamed parameter that only consists of a regexp. It works the same the named parameter, except it will be numerically indexed:
const regexp = pathToRegexp("/:foo/(.*)");
regexp.exec("/test/route");
Modifiers
Modifiers must be placed after the parameter (e.g. /:foo?
, /(test)?
, /:foo(test)?
, or {-:foo(test)}?
).
Optional
Parameters can be suffixed with a question mark (?
) to make the parameter optional.
const regexp = pathToRegexp("/:foo/:bar?");
regexp.exec("/test");
regexp.exec("/test/route");
Tip: The prefix is also optional, escape the prefix \/
to make it required.
When dealing with query strings, escape the question mark (?
) so it doesn't mark the parameter as optional. Handling unordered data is outside the scope of this library.
const regexp = pathToRegexp("/search/:tableName\\?useIndex=true&term=amazing");
regexp.exec("/search/people?useIndex=true&term=amazing");
regexp.exec("/search/people?term=amazing&useIndex=true");
Zero or more
Parameters can be suffixed with an asterisk (*
) to denote a zero or more parameter matches.
const regexp = pathToRegexp("/:foo*");
regexp.exec("/");
regexp.exec("/bar/baz");
One or more
Parameters can be suffixed with a plus sign (+
) to denote a one or more parameter matches.
const regexp = pathToRegexp("/:foo+");
regexp.exec("/");
regexp.exec("/bar/baz");
Match
The match
function will return a function for transforming paths into parameters:
const fn = match("/user/:id", { decode: decodeURIComponent });
fn("/user/123");
fn("/invalid");
fn("/user/caf%C3%A9");
Process Pathname
You should make sure variations of the same path match the expected path
. Here's one possible solution using encode
:
const fn = match("/café", { encode: encodeURI });
fn("/caf%C3%A9");
Note: URL
encodes paths, so /café
would be normalized to /caf%C3%A9
and match in the above example.
Alternative Using Normalize
Sometimes you won't have already normalized paths to use, so you could normalize it yourself before matching:
function normalizePathname(pathname: string) {
return (
decodeURI(pathname)
.replace(/\/+/g, "/")
.normalize()
);
}
const re = pathToRegexp("/caf\u00E9");
const input = encodeURI("/cafe\u0301");
re.test(input);
re.test(normalizePathname(input));
Parse
The parse
function will return a list of strings and keys from a path string:
const tokens = 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)
The compile
function will return a function for transforming parameters into a valid path:
const toPath = compile("/user/:id", { encode: encodeURIComponent });
toPath({ id: 123 });
toPath({ id: "café" });
toPath({ id: "/" });
toPath({ id: ":/" });
const toPathRaw = compile("/user/:id");
toPathRaw({ id: "%3A%2F" });
toPathRaw({ id: ":/" }, { validate: false });
const toPathRepeated = compile("/:segment+");
toPathRepeated({ segment: "foo" });
toPathRepeated({ segment: ["a", "b", "c"] });
const toPathRegexp = compile("/user/:id(\\d+)");
toPathRegexp({ id: 123 });
toPathRegexp({ id: "123" });
toPathRegexp({ id: "abc" });
toPathRegexp({ id: "abc" }, { validate: false });
Note: The generated function will throw on invalid input.
Working with Tokens
Path-To-RegExp exposes the two functions used internally that accept an array of tokens:
tokensToRegexp(tokens, keys?, options?)
Transform an array of tokens into a matching regular expression.tokensToFunction(tokens)
Transform an array of tokens into a path generator function.
Token Information
name
The name of the token (string
for named or number
for unnamed index)prefix
The prefix string for the segment (e.g. "/"
)suffix
The suffix string for the segment (e.g. ""
)pattern
The RegExp used to match this token (string
)modifier
The modifier character used for the segment (e.g. ?
)
Compatibility with Express <= 4.x
Path-To-RegExp breaks compatibility with Express <= 4.x
:
- RegExp special characters can only be used in a parameter
- Express.js 4.x supported
RegExp
special characters regardless of position - this is considered a bug
- Parameters have suffixes that augment meaning -
*
, +
and ?
. E.g. /:user*
- No wildcard asterisk (
*
) - use parameters instead ((.*)
or :splat*
)
Live Demo
You can see a live demo of this library in use at express-route-tester.
License
MIT