Gathering detailed insights and metrics for @qixian.cs/path-to-regexp
Gathering detailed insights and metrics for @qixian.cs/path-to-regexp
Gathering detailed insights and metrics for @qixian.cs/path-to-regexp
Gathering detailed insights and metrics for @qixian.cs/path-to-regexp
npm install @qixian.cs/path-to-regexp
Typescript
Module System
Node Version
NPM Version
92.7
Supply Chain
99.5
Quality
74.8
Maintenance
100
Vulnerability
100
License
Fix backtracking (again)
Published on 05 Dec 2024
8.2.0
Published on 26 Sept 2024
Error on bad input
Published on 12 Sept 2024
Fix backtracking in 6.x
Published on 12 Sept 2024
Add backtracking protection
Published on 10 Sept 2024
Fix backtracking in 1.x
Published on 10 Sept 2024
TypeScript (100%)
Total Downloads
4,631,283
Last Day
1,327
Last Week
8,257
Last Month
49,821
Last Year
789,089
8,266 Stars
343 Commits
389 Forks
64 Watching
6 Branches
51 Contributors
Minified
Minified + Gzipped
Latest Version
6.1.0
Package Id
@qixian.cs/path-to-regexp@6.1.0
Size
17.34 kB
NPM Version
6.14.5
Node Version
12.18.1
Publised On
07 Jul 2020
Cumulative downloads
Total Downloads
Last day
-45.4%
1,327
Compared to previous day
Last week
-37.2%
8,257
Compared to previous week
Last month
-7.9%
49,821
Compared to previous month
Last year
-45.4%
789,089
Compared to previous year
Turn a path string such as
/user/:name
into a regular expression.
npm install path-to-regexp --save
1const { pathToRegexp, match, parse, compile } = require("path-to-regexp"); 2 3// pathToRegexp(path, keys?, options?) 4// match(path) 5// parse(path) 6// compile(path)
true
the regexp will be case sensitive. (default: false
)true
the regexp allows an optional trailing delimiter to match. (default: false
)true
the regexp will match to the end of the string. (default: true
)true
the regexp will match from the beginning of the string. (default: true
)[^/#?]
for :named
patterns. (default: '/#?'
)RegExp
. (default: x => x
)./
)1const keys = []; 2const regexp = pathToRegexp("/foo/:bar", keys); 3// regexp = /^\/foo(?:\/([^\/#\?]+?))[\/#\?]?$/i 4// keys = [{ name: 'bar', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }]
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.
The path argument is used to define parameters and populate keys.
Named parameters are defined by prefixing a colon to the parameter name (:foo
).
1const regexp = pathToRegexp("/:foo/:bar"); 2// keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }] 3 4regexp.exec("/test/route"); 5//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
Please note: Parameter names must use "word characters" ([A-Za-z0-9_]
).
Parameters can have a custom regexp, which overrides the default match ([^/]+
). For example, you can match digits or names in a path:
1const regexpNumbers = pathToRegexp("/icon-:foo(\\d+).png"); 2// keys = [{ name: 'foo', ... }] 3 4regexpNumbers.exec("/icon-123.png"); 5//=> ['/icon-123.png', '123'] 6 7regexpNumbers.exec("/icon-abc.png"); 8//=> null 9 10const regexpWord = pathToRegexp("/(user|u)"); 11// keys = [{ name: 0, ... }] 12 13regexpWord.exec("/u"); 14//=> ['/u', 'u'] 15 16regexpWord.exec("/users"); 17//=> null
Tip: Backslashes need to be escaped with another backslash in JavaScript strings.
Parameters can be wrapped in {}
to create custom prefixes or suffixes for your segment:
1const regexp = pathToRegexp("/:attr1?{-:attr2}?{-:attr3}?"); 2 3regexp.exec("/test"); 4// => ['/test', 'test', undefined, undefined] 5 6regexp.exec("/test-test"); 7// => ['/test', 'test', 'test', undefined]
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:
1const regexp = pathToRegexp("/:foo/(.*)"); 2// keys = [{ name: 'foo', ... }, { name: 0, ... }] 3 4regexp.exec("/test/route"); 5//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
Modifiers must be placed after the parameter (e.g. /:foo?
, /(test)?
, /:foo(test)?
, or {-:foo(test)}?
).
Parameters can be suffixed with a question mark (?
) to make the parameter optional.
1const regexp = pathToRegexp("/:foo/:bar?"); 2// keys = [{ name: 'foo', ... }, { name: 'bar', prefix: '/', modifier: '?' }] 3 4regexp.exec("/test"); 5//=> [ '/test', 'test', undefined, index: 0, input: '/test', groups: undefined ] 6 7regexp.exec("/test/route"); 8//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]
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.
1const regexp = pathToRegexp("/search/:tableName\\?useIndex=true&term=amazing"); 2 3regexp.exec("/search/people?useIndex=true&term=amazing"); 4//=> [ '/search/people?useIndex=true&term=amazing', 'people', index: 0, input: '/search/people?useIndex=true&term=amazing', groups: undefined ] 5 6// This library does not handle query strings in different orders 7regexp.exec("/search/people?term=amazing&useIndex=true"); 8//=> null
Parameters can be suffixed with an asterisk (*
) to denote a zero or more parameter matches.
1const regexp = pathToRegexp("/:foo*"); 2// keys = [{ name: 'foo', prefix: '/', modifier: '*' }] 3 4regexp.exec("/"); 5//=> [ '/', undefined, index: 0, input: '/', groups: undefined ] 6 7regexp.exec("/bar/baz"); 8//=> [ '/bar/baz', 'bar/baz', index: 0, input: '/bar/baz', groups: undefined ]
Parameters can be suffixed with a plus sign (+
) to denote a one or more parameter matches.
1const regexp = pathToRegexp("/:foo+"); 2// keys = [{ name: 'foo', prefix: '/', modifier: '+' }] 3 4regexp.exec("/"); 5//=> null 6 7regexp.exec("/bar/baz"); 8//=> [ '/bar/baz','bar/baz', index: 0, input: '/bar/baz', groups: undefined ]
The match
function will return a function for transforming paths into parameters:
1// Make sure you consistently `decode` segments. 2const match = match("/user/:id", { decode: decodeURIComponent }); 3 4match("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } } 5match("/invalid"); //=> false 6match("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
You should make sure variations of the same path match the expected path
. Here's one possible solution using encode
:
1const match = match("/café", { encode: encodeURI, decode: decodeURIComponent }); 2 3match("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
Note: URL
automatically encodes pathnames for you.
Sometimes you won't have an already normalized pathname. You can normalize it yourself before processing:
1/**
2 * Normalize a pathname for matching, replaces multiple slashes with a single
3 * slash and normalizes unicode characters to "NFC". When using this method,
4 * `decode` should be an identity function so you don't decode strings twice.
5 */
6function normalizePathname(pathname: string) {
7 return (
8 decodeURI(pathname)
9 // Replaces repeated slashes in the URL.
10 .replace(/\/+/g, "/")
11 // Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
12 // Note: Missing native IE support, may want to skip this step.
13 .normalize()
14 );
15}
16
17// Two possible ways of writing `/café`:
18const re = pathToRegexp("/caf\u00E9");
19const input = encodeURI("/cafe\u0301");
20
21re.test(input); //=> false
22re.test(normalizePathname(input)); //=> true
The parse
function will return a list of strings and keys from a path string:
1const tokens = parse("/route/:foo/(.*)"); 2 3console.log(tokens[0]); 4//=> "/route" 5 6console.log(tokens[1]); 7//=> { name: 'foo', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' } 8 9console.log(tokens[2]); 10//=> { name: 0, prefix: '/', suffix: '', pattern: '.*', modifier: '' }
Note: This method only works with strings.
The compile
function will return a function for transforming parameters into a valid path:
1// Make sure you encode your path segments consistently.
2const toPath = compile("/user/:id", { encode: encodeURIComponent });
3
4toPath({ id: 123 }); //=> "/user/123"
5toPath({ id: "café" }); //=> "/user/caf%C3%A9"
6toPath({ id: "/" }); //=> "/user/%2F"
7
8toPath({ id: ":/" }); //=> "/user/%3A%2F"
9
10// Without `encode`, you need to make sure inputs are encoded correctly.
11const toPathRaw = compile("/user/:id");
12
13toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
14toPathRaw({ id: ":/" }, { validate: false }); //=> "/user/:/"
15
16const toPathRepeated = compile("/:segment+");
17
18toPathRepeated({ segment: "foo" }); //=> "/foo"
19toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
20
21const toPathRegexp = compile("/user/:id(\\d+)");
22
23toPathRegexp({ id: 123 }); //=> "/user/123"
24toPathRegexp({ id: "123" }); //=> "/user/123"
25toPathRegexp({ id: "abc" }); //=> Throws `TypeError`.
26toPathRegexp({ id: "abc" }, { validate: false }); //=> "/user/abc"
Note: The generated function will throw on invalid input.
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.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. ?
)Path-To-RegExp breaks compatibility with Express <= 4.x
:
RegExp
special characters regardless of position - this is considered a bug*
, +
and ?
. E.g. /:user*
*
) - use parameters instead ((.*)
or :splat*
)You can see a live demo of this library in use at express-route-tester.
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
2 out of 2 merged PRs checked by a CI test -- score normalized to 10
Reason
27 different organizations found -- score normalized to 10
Details
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
3 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
Reason
1 commit(s) out of 30 and 2 issue activity out of 30 found in the last 90 days -- score normalized to 2
Reason
branch protection not enabled on development/release branches
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
found 28 unreviewed changesets out of 30 -- score normalized to 0
Reason
no update tool detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-01-27T21:24:10Z
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More