basant307/AI_Governance_Project
048
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```javascript20const { pathToRegexp, match, parse, compile } = require("path-to-regexp");21 22// pathToRegexp(path, keys?, options?)23// match(path)24// parse(path)25// compile(path)26```27 28### Path to regexp29 30The `pathToRegexp` function will return a regular expression object based on the provided `path` argument. It accepts the following arguments:31 32- **path** A string, array of strings, or a regular expression.33- **keys** _(optional)_ An array to populate with keys found in the path.34- **options** _(optional)_35 - **sensitive** When `true` the regexp will be case sensitive. (default: `false`)36 - **strict** When `true` the regexp won't allow an optional trailing delimiter to match. (default: `false`)37 - **end** When `true` the regexp will match to the end of the string. (default: `true`)38 - **start** When `true` the regexp will match from the beginning of the string. (default: `true`)39 - **delimiter** The default delimiter for segments, e.g. `[^/#?]` for `:named` patterns. (default: `'/#?'`)40 - **endsWith** Optional character, or list of characters, to treat as "end" characters.41 - **encode** A function to encode strings before inserting into `RegExp`. (default: `x => x`)42 - **prefixes** List of characters to automatically consider prefixes when parsing. (default: `./`)43 44```javascript45const keys = [];46const regexp = pathToRegexp("/foo/:bar", keys);47// regexp = /^\/foo(?:\/([^\/#\?]+?))[\/#\?]?$/i48// keys = [{ name: 'bar', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }]49```50 51**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](#optional).52 53### Parameters54 55The path argument is used to define parameters and populate keys.56 57#### Named Parameters58 59Named parameters are defined by prefixing a colon to the parameter name (`:foo`).60 61```js62const regexp = pathToRegexp("/:foo/:bar");63// keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]64 65regexp.exec("/test/route");66//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]67```68 69**Please note:** Parameter names must use "word characters" (`[A-Za-z0-9_]`).70 71##### Custom Matching Parameters72 73Parameters can have a custom regexp, which overrides the default match (`[^/]+`). For example, you can match digits or names in a path:74 75```js76const regexpNumbers = pathToRegexp("/icon-:foo(\\d+).png");77// keys = [{ name: 'foo', ... }]78 79regexpNumbers.exec("/icon-123.png");80//=> ['/icon-123.png', '123']81 82regexpNumbers.exec("/icon-abc.png");83//=> null84 85const regexpWord = pathToRegexp("/(user|u)");86// keys = [{ name: 0, ... }]87 88regexpWord.exec("/u");89//=> ['/u', 'u']90 91regexpWord.exec("/users");92//=> null93```94 95**Tip:** Backslashes need to be escaped with another backslash in JavaScript strings.96 97##### Custom Prefix and Suffix98 99Parameters can be wrapped in `{}` to create custom prefixes or suffixes for your segment:100 101```js102const regexp = pathToRegexp("/:attr1?{-:attr2}?{-:attr3}?");103 104regexp.exec("/test");105// => ['/test', 'test', undefined, undefined]106 107regexp.exec("/test-test");108// => ['/test', 'test', 'test', undefined]109```110 111#### Unnamed Parameters112 113It 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:114 115```js116const regexp = pathToRegexp("/:foo/(.*)");117// keys = [{ name: 'foo', ... }, { name: 0, ... }]118 119regexp.exec("/test/route");120//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]121```122 123#### Modifiers124 125Modifiers must be placed after the parameter (e.g. `/:foo?`, `/(test)?`, `/:foo(test)?`, or `{-:foo(test)}?`).126 127##### Optional128 129Parameters can be suffixed with a question mark (`?`) to make the parameter optional.130 131```js132const regexp = pathToRegexp("/:foo/:bar?");133// keys = [{ name: 'foo', ... }, { name: 'bar', prefix: '/', modifier: '?' }]134 135regexp.exec("/test");136//=> [ '/test', 'test', undefined, index: 0, input: '/test', groups: undefined ]137 138regexp.exec("/test/route");139//=> [ '/test/route', 'test', 'route', index: 0, input: '/test/route', groups: undefined ]140```141 142**Tip:** The prefix is also optional, escape the prefix `\/` to make it required.143 144When 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.145 146```js147const regexp = pathToRegexp("/search/:tableName\\?useIndex=true&term=amazing");148 149regexp.exec("/search/people?useIndex=true&term=amazing");150//=> [ '/search/people?useIndex=true&term=amazing', 'people', index: 0, input: '/search/people?useIndex=true&term=amazing', groups: undefined ]151 152// This library does not handle query strings in different orders153regexp.exec("/search/people?term=amazing&useIndex=true");154//=> null155```156 157##### Zero or more158 159Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches.160 161```js162const regexp = pathToRegexp("/:foo*");163// keys = [{ name: 'foo', prefix: '/', modifier: '*' }]164 165regexp.exec("/");166//=> [ '/', undefined, index: 0, input: '/', groups: undefined ]167 168regexp.exec("/bar/baz");169//=> [ '/bar/baz', 'bar/baz', index: 0, input: '/bar/baz', groups: undefined ]170```171 172##### One or more173 174Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches.175 176```js177const regexp = pathToRegexp("/:foo+");178// keys = [{ name: 'foo', prefix: '/', modifier: '+' }]179 180regexp.exec("/");181//=> null182 183regexp.exec("/bar/baz");184//=> [ '/bar/baz','bar/baz', index: 0, input: '/bar/baz', groups: undefined ]185```186 187### Match188 189The `match` function will return a function for transforming paths into parameters:190 191```js192// Make sure you consistently `decode` segments.193const fn = match("/user/:id", { decode: decodeURIComponent });194 195fn("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } }196fn("/invalid"); //=> false197fn("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }198```199 200The `match` function can be used to custom match named parameters. For example, this can be used to whitelist a small number of valid paths:201 202```js203const urlMatch = match("/users/:id/:tab(home|photos|bio)", {204 decode: decodeURIComponent,205});206 207urlMatch("/users/1234/photos");208//=> { path: '/users/1234/photos', index: 0, params: { id: '1234', tab: 'photos' } }209 210urlMatch("/users/1234/bio");211//=> { path: '/users/1234/bio', index: 0, params: { id: '1234', tab: 'bio' } }212 213urlMatch("/users/1234/otherstuff");214//=> false215```216 217#### Process Pathname218 219You should make sure variations of the same path match the expected `path`. Here's one possible solution using `encode`:220 221```js222const fn = match("/café", { encode: encodeURI });223 224fn("/caf%C3%A9"); //=> { path: '/caf%C3%A9', index: 0, params: {} }225```226 227**Note:** [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) encodes paths, so `/café` would be normalized to `/caf%C3%A9` and match in the above example.228 229##### Alternative Using Normalize230 231Sometimes you won't have already normalized paths to use, so you could normalize it yourself before matching:232 233```js234/**235 * Normalize a pathname for matching, replaces multiple slashes with a single236 * slash and normalizes unicode characters to "NFC". When using this method,237 * `decode` should be an identity function so you don't decode strings twice.238 */239function normalizePathname(pathname: string) {240 return (241 decodeURI(pathname)242 // Replaces repeated slashes in the URL.243 .replace(/\/+/g, "/")244 // Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize245 // Note: Missing native IE support, may want to skip this step.246 .normalize()247 );248}249 250// Two possible ways of writing `/café`:251const re = pathToRegexp("/caf\u00E9");252const input = encodeURI("/cafe\u0301");253 254re.test(input); //=> false255re.test(normalizePathname(input)); //=> true256```257 258### Parse259 260The `parse` function will return a list of strings and keys from a path string:261 262```js263const tokens = parse("/route/:foo/(.*)");264 265console.log(tokens[0]);266//=> "/route"267 268console.log(tokens[1]);269//=> { name: 'foo', prefix: '/', suffix: '', pattern: '[^\\/#\\?]+?', modifier: '' }270 271console.log(tokens[2]);272//=> { name: 0, prefix: '/', suffix: '', pattern: '.*', modifier: '' }273```274 275**Note:** This method only works with strings.276 277### Compile ("Reverse" Path-To-RegExp)278 279The `compile` function will return a function for transforming parameters into a valid path:280 281```js282// Make sure you encode your path segments consistently.283const toPath = compile("/user/:id", { encode: encodeURIComponent });284 285toPath({ id: 123 }); //=> "/user/123"286toPath({ id: "café" }); //=> "/user/caf%C3%A9"287toPath({ id: ":/" }); //=> "/user/%3A%2F"288 289// Without `encode`, you need to make sure inputs are encoded correctly.290// (Note: You can use `validate: false` to create an invalid paths.)291const toPathRaw = compile("/user/:id", { validate: false });292 293toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"294toPathRaw({ id: ":/" }); //=> "/user/:/"295 296const toPathRepeated = compile("/:segment+");297 298toPathRepeated({ segment: "foo" }); //=> "/foo"299toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"300 301const toPathRegexp = compile("/user/:id(\\d+)");302 303toPathRegexp({ id: 123 }); //=> "/user/123"304toPathRegexp({ id: "123" }); //=> "/user/123"305```306 307**Note:** The generated function will throw on invalid input.308 309### Working with Tokens310 311Path-To-RegExp exposes the two functions used internally that accept an array of tokens:312 313- `tokensToRegexp(tokens, keys?, options?)` Transform an array of tokens into a matching regular expression.314- `tokensToFunction(tokens)` Transform an array of tokens into a path generator function.315 316#### Token Information317 318- `name` The name of the token (`string` for named or `number` for unnamed index)319- `prefix` The prefix string for the segment (e.g. `"/"`)320- `suffix` The suffix string for the segment (e.g. `""`)321- `pattern` The RegExp used to match this token (`string`)322- `modifier` The modifier character used for the segment (e.g. `?`)323 324## Compatibility with Express <= 4.x325 326Path-To-RegExp breaks compatibility with Express <= `4.x`:327 328- RegExp special characters can only be used in a parameter329 - Express.js 4.x supported `RegExp` special characters regardless of position - this is considered a bug330- Parameters have suffixes that augment meaning - `*`, `+` and `?`. E.g. `/:user*`331- No wildcard asterisk (`*`) - use parameters instead (`(.*)` or `:splat*`)332 333## Live Demo334 335You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.io/express-route-tester/).336 337## License338 339MIT340 341[npm-image]: https://img.shields.io/npm/v/path-to-regexp342[npm-url]: https://npmjs.org/package/path-to-regexp343[downloads-image]: https://img.shields.io/npm/dm/path-to-regexp344[downloads-url]: https://npmjs.org/package/path-to-regexp345[build-image]: https://img.shields.io/github/actions/workflow/status/pillarjs/path-to-regexp/ci.yml?branch=master346[build-url]: https://github.com/pillarjs/path-to-regexp/actions/workflows/ci.yml?query=branch%3Amaster347[coverage-image]: https://img.shields.io/codecov/c/gh/pillarjs/path-to-regexp348[coverage-url]: https://codecov.io/gh/pillarjs/path-to-regexp349[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat350[license-url]: LICENSE.md351 