AK-21/Graphite-Industrial-Intelligence
0
1# Path-to-RegExp2 3> Turn a path string such as `/user/:name` into a regular expression.4 5[![NPM version][npm-image]][npm-url]6[![NPM downloads][downloads-image]][downloads-url]7[![Build status][build-image]][build-url]8[![Build coverage][coverage-image]][coverage-url]9[![License][license-image]][license-url]10 11## Installation12 13```14npm install path-to-regexp --save15```16 17## Usage18 19```js20const {21 match,22 pathToRegexp,23 compile,24 parse,25 stringify,26} = require("path-to-regexp");27```28 29### Parameters30 31Parameters 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"`).32 33```js34const fn = match("/:foo/:bar");35 36fn("/test/route");37//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }38```39 40### Wildcard41 42Wildcard 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`).43 44```js45const fn = match("/*splat");46 47fn("/bar/baz");48//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }49```50 51### Optional52 53Braces can be used to define parts of the path that are optional.54 55```js56const fn = match("/users{/:id}/delete");57 58fn("/users/delete");59//=> { path: '/users/delete', params: {} }60 61fn("/users/123/delete");62//=> { path: '/users/123/delete', params: { id: '123' } }63```64 65## Match66 67The `match` function returns a function for matching strings against a path:68 69- **path** String, `TokenData` object, or array of strings and `TokenData` objects.70- **options** _(optional)_ (Extends [pathToRegexp](#pathToRegexp) options)71 - **decode** Function for decoding strings to params, or `false` to disable all processing. (default: `decodeURIComponent`)72 73```js74const fn = match("/foo/:bar");75```76 77**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).78 79## PathToRegexp80 81The `pathToRegexp` function returns the `regexp` for matching strings against paths, and an array of `keys` for understanding the `RegExp#exec` matches.82 83- **path** String, `TokenData` object, or array of strings and `TokenData` objects.84- **options** _(optional)_ (See [parse](#parse) for more options)85 - **sensitive** Regexp will be case sensitive. (default: `false`)86 - **end** Validate the match reaches the end of the string. (default: `true`)87 - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`)88 - **trailing** Allows optional trailing delimiter to match. (default: `true`)89 90```js91const { regexp, keys } = pathToRegexp("/foo/:bar");92 93regexp.exec("/foo/123"); //=> ["/foo/123", "123"]94```95 96## Compile ("Reverse" Path-To-RegExp)97 98The `compile` function will return a function for transforming parameters into a valid path:99 100- **path** A string or `TokenData` object.101- **options** (See [parse](#parse) for more options)102 - **delimiter** The default delimiter for segments, e.g. `[^/]` for `:named` parameters. (default: `'/'`)103 - **encode** Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)104 105```js106const toPath = compile("/user/:id");107 108toPath({ id: "name" }); //=> "/user/name"109toPath({ id: "café" }); //=> "/user/caf%C3%A9"110 111const toPathRepeated = compile("/*segment");112 113toPathRepeated({ segment: ["foo"] }); //=> "/foo"114toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"115 116// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.117const toPathRaw = compile("/user/:id", { encode: false });118 119toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"120```121 122## Stringify123 124Transform a `TokenData` object to a Path-to-RegExp string.125 126- **data** A `TokenData` object.127 128```js129const data = {130 tokens: [131 { type: "text", value: "/" },132 { type: "param", name: "foo" },133 ],134};135 136const path = stringify(data); //=> "/:foo"137```138 139## Developers140 141- If you are rewriting paths with match and compile, consider using `encode: false` and `decode: false` to keep raw paths passed around.142- To ensure matches work on paths containing characters usually encoded, such as emoji, consider using [encodeurl](https://github.com/pillarjs/encodeurl) for `encodePath`.143 144### Parse145 146The `parse` function accepts a string and returns `TokenData`, which can be used with `match` and `compile`.147 148- **path** A string.149- **options** _(optional)_150 - **encodePath** A function for encoding input strings. (default: `x => x`, recommended: [`encodeurl`](https://github.com/pillarjs/encodeurl))151 152### Tokens153 154`TokenData` has two properties:155 156- **tokens** A sequence of tokens, currently of types `text`, `param`, `wildcard`, or `group`.157- **originalPath** The original path used with `parse`, shown in error messages to assist debugging.158 159### Custom path160 161In some applications you may not be able to use the `path-to-regexp` syntax, but you still want to use this library for `match` and `compile`. For example:162 163```js164import { match } from "path-to-regexp";165 166const tokens = [167 { type: "text", value: "/" },168 { type: "param", name: "foo" },169];170const originalPath = "/[foo]"; // To help debug error messages.171const path = { tokens, originalPath };172const fn = match(path);173 174fn("/test"); //=> { path: '/test', params: { foo: 'test' } }175```176 177## Errors178 179An 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.180 181### Missing parameter name182 183Parameter names must be provided after `:` or `*`, for example `/*path`. They can be valid JavaScript identifiers (e.g. `:myName`) or JSON strings (`:"my-name"`).184 185### Unexpected `?` or `+`186 187In past releases, `?`, `*`, and `+` were used to denote optional or repeating parameters. As an alternative, try these:188 189- For optional (`?`), use braces: `/file{.:ext}`.190- For one or more (`+`), use a wildcard: `/*path`.191- For zero or more (`*`), use both: `/files{/*path}`.192 193### Unexpected `(`, `)`, `[`, `]`, etc.194 195Previous 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. `"\\("`.196 197### Unterminated quote198 199Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, `:"foo`.200 201### Express <= 4.x202 203Path-To-RegExp breaks compatibility with Express <= `4.x` in the following ways:204 205- The wildcard `*` must have a name and matches the behavior of parameters `:`.206- The optional character `?` is no longer supported, use braces instead: `/:file{.:ext}`.207- Regexp characters are not supported.208- Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`).209- Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`.210 211## License212 213MIT214 215[npm-image]: https://img.shields.io/npm/v/path-to-regexp216[npm-url]: https://npmjs.org/package/path-to-regexp217[downloads-image]: https://img.shields.io/npm/dm/path-to-regexp218[downloads-url]: https://npmjs.org/package/path-to-regexp219[build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master220[build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster221[coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp222[coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp223[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat224[license-url]: LICENSE.md225 