Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork447
Turn a path string such as `/user/:name` into a regular expression
License
pillarjs/path-to-regexp
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Turn a path string such as
/user/:nameinto a regular expression.
npm install path-to-regexp --saveconst{ match, pathToRegexp, compile, parse, stringify,}=require("path-to-regexp");
Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name").
constfn=match("/:foo/:bar");fn("/test/route");//=> { path: '/test/route', params: { foo: 'test', bar: 'route' }}
Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo).
constfn=match("/*splat");fn("/bar/baz");//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] }}
Braces can be used to define parts of the path that are optional.
constfn=match("/users{/:id}/delete");fn("/users/delete");//=> { path: '/users/delete', params: {}}fn("/users/123/delete");//=> { path: '/users/123/delete', params: { id: '123' }}
Thematch function returns a function for matching strings against a path:
- path String,
TokenDataobject, or array of strings andTokenDataobjects. - options(optional) (ExtendspathToRegexp options)
- decode Function for decoding strings to params, or
falseto disable all processing. (default:decodeURIComponent)
- decode Function for decoding strings to params, or
constfn=match("/foo/:bar");
Please note:path-to-regexp is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
ThepathToRegexp function returns theregexp for matching strings against paths, and an array ofkeys for understanding theRegExp#exec matches.
- path String,
TokenDataobject, or array of strings andTokenDataobjects. - options(optional) (Seeparse for more options)
- sensitive Regexp will be case sensitive. (default:
false) - end Validate the match reaches the end of the string. (default:
true) - delimiter The default delimiter for segments, e.g.
[^/]for:namedparameters. (default:'/') - trailing Allows optional trailing delimiter to match. (default:
true)
- sensitive Regexp will be case sensitive. (default:
const{ regexp, keys}=pathToRegexp("/foo/:bar");regexp.exec("/foo/123");//=> ["/foo/123", "123"]
Thecompile function will return a function for transforming parameters into a valid path:
- path A string or
TokenDataobject. - options (Seeparse for more options)
- delimiter The default delimiter for segments, e.g.
[^/]for:namedparameters. (default:'/') - encode Function for encoding input strings for output into the path, or
falseto disable entirely. (default:encodeURIComponent)
- delimiter The default delimiter for segments, e.g.
consttoPath=compile("/user/:id");toPath({id:"name"});//=> "/user/name"toPath({id:"café"});//=> "/user/caf%C3%A9"consttoPathRepeated=compile("/*segment");toPathRepeated({segment:["foo"]});//=> "/foo"toPathRepeated({segment:["a","b","c"]});//=> "/a/b/c"// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.consttoPathRaw=compile("/user/:id",{encode:false});toPathRaw({id:"%3A%2F"});//=> "/user/%3A%2F"
Transform aTokenData object to a Path-to-RegExp string.
- data A
TokenDataobject.
constdata={tokens:[{type:"text",value:"/"},{type:"param",name:"foo"},],};constpath=stringify(data);//=> "/:foo"
- If you are rewriting paths with match and compile, consider using
encode: falseanddecode: falseto keep raw paths passed around. - To ensure matches work on paths containing characters usually encoded, such as emoji, consider usingencodeurl for
encodePath.
Theparse function accepts a string and returnsTokenData, which can be used withmatch andcompile.
- path A string.
- options(optional)
- encodePath A function for encoding input strings. (default:
x => x, recommended:encodeurl)
- encodePath A function for encoding input strings. (default:
TokenData has two properties:
- tokens A sequence of tokens, currently of types
text,parameter,wildcard, orgroup. - originalPath The original path used with
parse, shown in error messages to assist debugging.
In some applications you may not be able to use thepath-to-regexp syntax, but you still want to use this library formatch andcompile. For example:
import{match}from"path-to-regexp";consttokens=[{type:"text",value:"/"},{type:"parameter",name:"foo"},];constoriginalPath="/[foo]";// To help debug error messages.constpath={ tokens, originalPath};constfn=match(path);fn("/test");//=> { path: '/test', index: 0, params: { foo: 'test' }}
An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.
Parameter names must be provided after: or*, for example/*path. They can be valid JavaScript identifiers (e.g.:myName) or JSON strings (:"my-name").
In past releases,?,*, and+ were used to denote optional or repeating parameters. As an alternative, try these:
- For optional (
?), use braces:/file{.:ext}. - For one or more (
+), use a wildcard:/*path. - For zero or more (
*), use both:/files{/*path}.
Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To match these characters literally, escape them with a backslash, e.g."\\(".
Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example,:"foo.
Path-To-RegExp breaks compatibility with Express <=4.x in the following ways:
- The wildcard
*must have a name and matches the behavior of parameters:. - The optional character
?is no longer supported, use braces instead:/:file{.:ext}. - Regexp characters are not supported.
- Some characters have been reserved to avoid confusion during upgrade (
()[]?+!). - Parameter names now support valid JavaScript identifiers, or quoted like
:"this".
MIT
About
Turn a path string such as `/user/:name` into a regular expression
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.