pathname-to-regexp
v1.0.0
Published
A robust JavaScript pathname parser, compiler, and matcher. Supports named parameters, wildcards, optional groups, custom delimiters, and generates optimized regular expressions.
Maintainers
Readme
PathnameToRegexp
PathnameToRegexp is a JavaScript pathname parser, compiler, matcher, and regular-expression generator. It supports named parameters, wildcards, optional groups, escaped characters, quoted parameter names, custom delimiters, encoding and decoding, and conversion between pathname patterns and token data.
Features
- Parse pathname patterns into immutable token data.
- Compile named parameters and wildcards into pathnames.
- Match pathnames and extract parameters.
- Generate regular expressions from pathname patterns.
- Support named parameters and wildcards.
- Support optional and nested groups.
- Support quoted parameter and wildcard names.
- Support escaped syntax characters.
- Support custom delimiters.
- Support custom encoding and decoding functions.
- Support both ES Modules and CommonJS.
- Include TypeScript type definitions.
Table of Contents
- API Summary
new PathnameToRegexp(pathname, [options])- Instance Properties
compile([options])match(input, [options])stringify()PathnameToRegexp.create(pathname, [options])PathnameToRegexp.parse(pathname, [options])PathnameToRegexp.compile(pathname, [options])PathnameToRegexp.match(pathname, [options])PathnameToRegexp.stringify(data)pathnameToRegexp(pathname, [options])
Installation
You can install PathnameToRegexp via npm:
npm install pathname-to-regexpRequirements
- Node.js
>=22
Importing
To use PathnameToRegexp in your JavaScript application, first import it.
ES Modules
import PathnameToRegexp, {
parse,
compile,
match,
stringify,
pathnameToRegexp,
} from 'pathname-to-regexp';CommonJS
const {
default: PathnameToRegexp,
parse,
compile,
match,
stringify,
pathnameToRegexp,
} = require('pathname-to-regexp');TypeScript type definitions are included for TypeScript consumers.
Usage
Creating an Instance
Create a PathnameToRegexp instance from a pathname pattern:
const pathname = new PathnameToRegexp('/users/:id');The instance parses the pattern and generates the regular expression used for matching.
pathname.tokens;
// [
// { type: 'text', value: '/users/' },
// { type: 'param', name: 'id' }
// ]
pathname.originalPathname;
// '/users/:id'
pathname.regexp;
// /^\/users\/([^/]+)(?:\/)?$/i
pathname.keys;
// [{ type: 'param', name: 'id' }]
pathname.delimiter;
// '/'Instances can then be used to compile parameter values, match pathnames, or stringify their parsed representation.
Compiling Parameters
Use compile() to create a function that converts parameter values into a pathname:
const compile = new PathnameToRegexp('/users/:id').compile();
compile({ id: '42' });
// '/users/42'Parameter values are encoded with encodeURIComponent by default:
const compile = new PathnameToRegexp('/users/:id').compile();
compile({ id: 'hello world' });
// '/users/hello%20world'Encoding can be disabled:
const compile = new PathnameToRegexp('/users/:id').compile({
encode: false,
});
compile({ id: 'hello world' });
// '/users/hello world'A custom encoder can also be supplied:
const compile = new PathnameToRegexp('/users/:id').compile({
encode: value => value.toUpperCase(),
});
compile({ id: 'abc' });
// '/users/ABC'Note:
encodeis a compile option. It is passed tocompile()and controls how parameter values are encoded when generating a pathname.
Matching Pathnames
Use match() to match an input pathname against the pattern:
const pathname = new PathnameToRegexp('/users/:id');
pathname.match('/users/42');
// {
// pathname: '/users/42',
// params: { id: '42' }
// }When the pathname does not match, match() returns false:
pathname.match('/posts/42');
// falseMatched parameters are decoded with decodeURIComponent by default:
const pathname = new PathnameToRegexp('/users/:id');
pathname.match('/users/hello%20world');
// {
// pathname: '/users/hello%20world',
// params: { id: 'hello world' }
// }Decoding can be disabled:
pathname.match('/users/hello%20world', {
decode: false,
});
// {
// pathname: '/users/hello%20world',
// params: { id: 'hello%20world' }
// }Note:
decodeis a match option. It is passed tomatch()and controls how captured parameter values are decoded.
Parsing Patterns
Use parse() to obtain the token representation of a pathname pattern:
const data = PathnameToRegexp.parse('/users/:id');
data;
// {
// tokens: [
// { type: 'text', value: '/users/' },
// { type: 'param', name: 'id' }
// ],
// originalPathname: '/users/:id'
// }The returned token data is immutable.
Stringifying Patterns
Use stringify() to convert parsed token data back into pathname pattern syntax:
const data = PathnameToRegexp.parse('/users/:id');
PathnameToRegexp.stringify(data);
// '/users/:id'A pathname string can also be passed directly:
PathnameToRegexp.stringify('/users/:id');
// '/users/:id'Stringification preserves parameter names and reconstructs escaped or quoted names when necessary.
Generating a Regular Expression
Use pathnameToRegexp() when only the generated regular expression and its keys are needed:
const { regexp, keys } = pathnameToRegexp('/users/:id');
regexp.test('/users/42');
// true
keys;
// [{ type: 'param', name: 'id' }]This is equivalent to creating an instance and reading its regexp and keys properties.
Pathname Syntax
PathnameToRegexp supports literal text, named parameters, wildcards, optional groups, quoted names, and escaped syntax characters.
Text
Literal text is matched exactly according to the configured matching options:
/users
/users/profile
/api/v1/usersFor example:
const pathname = new PathnameToRegexp('/users');
pathname.match('/users');
// { pathname: '/users', params: {} }
pathname.match('/posts');
// falseParameters
Named parameters begin with : followed by a parameter name:
/users/:id
/posts/:postId/comments/:commentIdThey capture a single pathname segment.
const pathname = new PathnameToRegexp('/users/:id');
pathname.match('/users/42');
// {
// pathname: '/users/42',
// params: { id: '42' }
// }Parameters can be compiled by providing a string value with the corresponding name:
const compile = new PathnameToRegexp('/users/:id').compile();
compile({ id: '42' });
// '/users/42'Parameter values must be non-empty strings.
Wildcards
Wildcards begin with * followed by a parameter name:
/files/*pathWildcards capture multiple pathname segments and are represented as arrays when matched:
const pathname = new PathnameToRegexp('/files/*path');
pathname.match('/files/src/lib/index.js');
// {
// pathname: '/files/src/lib/index.js',
// params: {
// path: ['src', 'lib', 'index.js']
// }
// }Wildcards are compiled from non-empty arrays of strings:
const compile = new PathnameToRegexp('/files/*path').compile();
compile({
path: ['src', 'lib', 'index.js'],
});
// '/files/src/lib/index.js'Each wildcard array item is encoded independently.
Groups
Groups are enclosed in { and }:
/users{/:id}Groups are optional.
The following pattern matches both pathnames:
const pathname = new PathnameToRegexp('/users{/:id}');
pathname.match('/users');
// { pathname: '/users', params: {} }
pathname.match('/users/42');
// { pathname: '/users/42', params: { id: '42' } }Groups can contain nested groups:
/users{/:id{/edit}}This pattern supports:
/users
/users/42
/users/42/editWhen compiling, a group is treated atomically. If a required parameter inside the group is missing, the entire group is omitted:
const compile = new PathnameToRegexp('/users{/:id{/action/:action}}').compile();
compile({});
// '/users'
compile({ id: '42' });
// '/users/42'
compile({ id: '42', action: 'edit' });
// '/users/42/action/edit'Quoted Names
Parameter and wildcard names may be quoted when they cannot be represented as regular identifiers:
/users/:"user-id"
/files/*"file-path"Quoted names may contain escaped characters:
/:"user\"id"
/:"user\\id"NOTE
// In JavaScript, backslashes within double quotes must be escaped.
const pathname = new PathnameToRegexp('/users/:"user\\"id"');
pathname.match('/users/my"id');
// { pathname: '/users/my"id', params: { 'user"id': 'my"id' } }The resulting parameter name is the unescaped quoted value.
const pathname = new PathnameToRegexp('/users/:\"user-id\"');
pathname.match('/users/42');
// {
// pathname: '/users/42',
// params: {
// 'user-id': '42'
// }
// }stringify() automatically uses quoted syntax when required.
Escaping
Pathname syntax characters can be escaped with \ when they should be interpreted as literal text.
For example:
/users/\:idrepresents the literal pathname:
/users/:idThe same applies to other syntax characters such as *, {, }, (, ), [, ], +, ?, and !.
Options
Different options are used at different stages of pathname processing.
Constructor Options
The constructor accepts the following options:
| Property | Type | Default | Description |
| ---------------- | ---------- | -------- | ------------------------------------------------------------------------ |
| delimiter | string | '/' | Default segment delimiter used when compiling and matching pathnames. |
| end | boolean | true | Whether the generated regular expression must match the entire pathname. |
| sensitive | boolean | false | Whether pathname matching is case-sensitive. |
| trailing | boolean | true | Whether a trailing / is accepted. |
| encodePathname | Function | identity | Function used to transform literal pathname text while parsing. |
Example:
const pathname = new PathnameToRegexp('/Users/:id', {
sensitive: true,
trailing: false,
});Note:
end,sensitive, andtrailingare constructor options. They configure the generated regular expression and are not options passed tomatch()orcompile().
Compile Options
compile() accepts:
| Property | Type | Default | Description |
| ----------- | ------------------- | -------------------- | ------------------------------------------------------------------------- |
| encode | Function \| false | encodeURIComponent | Function used to encode parameter values, or false to disable encoding. |
| delimiter | string | Instance delimiter | Segment delimiter used when compiling wildcard values. |
Example:
const compile = new PathnameToRegexp('/files/*path').compile({
encode: encodeURIComponent,
delimiter: '/',
});Match Options
match() accepts:
| Property | Type | Default | Description |
| ----------- | ------------------- | -------------------- | ----------------------------------------------------------------------- |
| decode | Function \| false | decodeURIComponent | Function used to decode matched values, or false to disable decoding. |
| delimiter | string | Instance delimiter | Segment delimiter used when decoding wildcard values. |
Example:
const pathname = new PathnameToRegexp('/files/*path');
pathname.match('/files/src/lib', {
decode: false,
});The decode option applies to both named parameters and wildcard segments.
Parse Options
parse() accepts:
| Property | Type | Default | Description |
| ---------------- | ---------- | -------- | ---------------------------------------------------------------- |
| encodePathname | Function | identity | Function used to transform literal pathname text during parsing. |
Example:
const data = PathnameToRegexp.parse('/users/:id', {
encodePathname: text => text.toLowerCase(),
});The transformed literal text is stored in the resulting tokens. Consequently, stringifying the parsed data may not reproduce the original pathname verbatim when a custom encoder transforms literal text.
API
API Summary
| Export | Description |
| -------------------- | -------------------------------------------------------------------------- |
| PathnameToRegexp | Main pathname parser, compiler, matcher, and regular-expression generator. |
| parse() | Parses a pathname pattern into token data. |
| compile() | Creates a function for compiling parameters into a pathname. |
| match() | Creates a function for matching pathnames. |
| stringify() | Converts pathname patterns or token data back into pathname syntax. |
| pathnameToRegexp() | Generates a regular expression and its associated parameter keys. |
The package also supports the equivalent static methods on PathnameToRegexp where applicable.
new PathnameToRegexp(pathname, [options])
Creates a pathname parser, compiler, matcher, and regular-expression generator.
const pathname = new PathnameToRegexp('/users/:id');Constructor Parameters
| Name | Type | Description |
| ---------- | ------------------------- | ----------------------------------------------- |
| pathname | string | Pathname pattern to parse. |
| options | PathnameToRegexpOptions | Optional parser and regular-expression options. |
The pathname must be a non-empty string beginning with /.
Instance Properties
tokens
Returns the immutable parsed token representation:
const pathname = new PathnameToRegexp('/users/:id');
pathname.tokens;
// [
// { type: 'text', value: '/users/' },
// { type: 'param', name: 'id' }
// ]originalPathname
Returns the original pathname pattern supplied to the constructor:
pathname.originalPathname;
// '/users/:id'regexp
Returns the generated regular expression:
pathname.regexp;keys
Returns the immutable parameter and wildcard tokens associated with the regular-expression capture groups:
pathname.keys;
// [{ type: 'param', name: 'id' }]delimiter
Returns the pathname segment delimiter configured for the instance:
pathname.delimiter;
// '/'compile([options])
Creates a compiler function for the pathname pattern.
const compile = new PathnameToRegexp('/users/:id').compile();
compile({ id: '42' });
// '/users/42'The returned compiler accepts a parameter object:
compile({ id: '42' });Named parameters require string values. Wildcards require non-empty arrays of strings.
Missing required parameters cause a PathnameToRegexpError.
match(input, [options])
Matches an input pathname against the compiled pattern.
const pathname = new PathnameToRegexp('/users/:id');
pathname.match('/users/42');
// {
// pathname: '/users/42',
// params: { id: '42' }
// }Returns false when the pathname does not match.
pathname.match('/posts/42');
// falsestringify()
Converts the instance token data back into pathname pattern syntax:
const pathname = new PathnameToRegexp('/users/:id');
pathname.stringify();
// '/users/:id'PathnameToRegexp.create(pathname, [options])
Creates a PathnameToRegexp instance.
const pathname = PathnameToRegexp.create('/users/:id');
pathname.match('/users/42');
// {
// pathname: '/users/42',
// params: { id: '42' }
// }This is equivalent to:
const pathname = new PathnameToRegexp('/users/:id');PathnameToRegexp.parse(pathname, [options])
Parses a pathname pattern into token data:
const data = PathnameToRegexp.parse('/users/:id');
data.tokens;
// [
// { type: 'text', value: '/users/' },
// { type: 'param', name: 'id' }
// ]PathnameToRegexp.compile(pathname, [options])
Creates a pathname compiler directly from a pathname pattern:
const compile = PathnameToRegexp.compile('/users/:id');
compile({ id: '42' });
// '/users/42'PathnameToRegexp.match(pathname, [options])
Creates a pathname matcher directly from a pathname pattern:
const match = PathnameToRegexp.match('/users/:id');
match('/users/42');
// {
// pathname: '/users/42',
// params: { id: '42' }
// }Matching options are supplied when the returned matcher is called:
const match = PathnameToRegexp.match('/users/:id');
match('/users/hello%20world', {
decode: false,
});PathnameToRegexp.stringify(data)
Stringifies either a pathname pattern or parsed pathname token data.
PathnameToRegexp.stringify('/users/:id');
// '/users/:id'It also accepts the result of parse():
const data = PathnameToRegexp.parse('/users/:id');
PathnameToRegexp.stringify(data);
// '/users/:id'pathnameToRegexp(pathname, [options])
Creates a regular expression and its associated parameter keys from a pathname pattern:
const { regexp, keys } = pathnameToRegexp('/users/:id');
regexp.test('/users/42');
// true
keys;
// [{ type: 'param', name: 'id' }]This helper is useful when only the regular expression and capture keys are required.
Errors
PathnameToRegexp uses standard JavaScript errors for invalid argument types and values, and PathnameToRegexpError for pathname-specific processing errors.
TypeError
A TypeError is thrown when an argument or option has an invalid type.
For example:
new PathnameToRegexp(123);
// TypeErrorRangeError
A RangeError is thrown when a value has the correct type but is outside the allowed range.
For example:
new PathnameToRegexp('');
// RangeErrorPathnameToRegexpError
A PathnameToRegexpError is thrown for pathname-specific errors, including invalid syntax, missing parameters, invalid parameter values, and excessive regular-expression combinations.
Examples include:
MISSING_PARAMETER_NAMEUNEXPECTED_TOKENUNEXPECTED_ENDUNEXPECTED_END_AFTER_ESCAPEUNTERMINATED_QUOTEMISSING_PARAMETERSEXPECTED_STRINGEXPECTED_ARRAYEXPECTED_ARRAY_ITEM_STRINGTOO_MANY_COMBINATIONSUNKNOWN_TOKEN_TYPEMISSING_TEXT_BEFORE_TOKEN
For example:
const compile = new PathnameToRegexp('/users/:id').compile();
compile({});
// PathnameToRegexpErrorThe error includes a domain-specific error code and contextual details when applicable.
Contributing
If you encounter a bug or have an idea for improving PathnameToRegexp, please open an issue on the GitHub repository.
Pull requests are also welcome.
Before submitting a change, make sure the existing test suite passes and that new behavior is covered by appropriate tests.
License
PathnameToRegexp is released under the MIT License.
