You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 3 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # Path-to-RegExp
  2. > Turn an Express-style path string such as `/user/:name` into a regular expression.
  3. [![NPM version][npm-image]][npm-url]
  4. [![Build status][travis-image]][travis-url]
  5. [![Test coverage][coveralls-image]][coveralls-url]
  6. [![Dependency Status][david-image]][david-url]
  7. [![License][license-image]][license-url]
  8. [![Downloads][downloads-image]][downloads-url]
  9. ## Installation
  10. ```
  11. npm install path-to-regexp --save
  12. ```
  13. ## Usage
  14. ```javascript
  15. var pathToRegexp = require('path-to-regexp')
  16. // pathToRegexp(path, keys, options)
  17. // pathToRegexp.parse(path)
  18. // pathToRegexp.compile(path)
  19. ```
  20. - **path** An Express-style string, an array of strings, or a regular expression.
  21. - **keys** An array to be populated with the keys found in the path.
  22. - **options**
  23. - **sensitive** When `true` the route will be case sensitive. (default: `false`)
  24. - **strict** When `false` the trailing slash is optional. (default: `false`)
  25. - **end** When `false` the path will match at the beginning. (default: `true`)
  26. - **delimiter** Set the default delimiter for repeat parameters. (default: `'/'`)
  27. ```javascript
  28. var keys = []
  29. var re = pathToRegexp('/foo/:bar', keys)
  30. // re = /^\/foo\/([^\/]+?)\/?$/i
  31. // keys = [{ name: 'bar', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }]
  32. ```
  33. **Please note:** The `RegExp` returned by `path-to-regexp` is intended for use with pathnames or hostnames. It can not handle the query strings or fragments of a URL.
  34. ### Parameters
  35. The path string can be used to define parameters and populate the keys.
  36. #### Named Parameters
  37. Named parameters are defined by prefixing a colon to the parameter name (`:foo`). By default, the parameter will match until the following path segment.
  38. ```js
  39. var re = pathToRegexp('/:foo/:bar', keys)
  40. // keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]
  41. re.exec('/test/route')
  42. //=> ['/test/route', 'test', 'route']
  43. ```
  44. **Please note:** Named parameters must be made up of "word characters" (`[A-Za-z0-9_]`).
  45. ```js
  46. var re = pathToRegexp('/(apple-)?icon-:res(\\d+).png', keys)
  47. // keys = [{ name: 0, prefix: '/', ... }, { name: 'res', prefix: '', ... }]
  48. re.exec('/icon-76.png')
  49. //=> ['/icon-76.png', undefined, '76']
  50. ```
  51. #### Modified Parameters
  52. ##### Optional
  53. Parameters can be suffixed with a question mark (`?`) to make the parameter optional. This will also make the prefix optional.
  54. ```js
  55. var re = pathToRegexp('/:foo/:bar?', keys)
  56. // keys = [{ name: 'foo', ... }, { name: 'bar', delimiter: '/', optional: true, repeat: false }]
  57. re.exec('/test')
  58. //=> ['/test', 'test', undefined]
  59. re.exec('/test/route')
  60. //=> ['/test', 'test', 'route']
  61. ```
  62. ##### Zero or more
  63. Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches. The prefix is taken into account for each match.
  64. ```js
  65. var re = pathToRegexp('/:foo*', keys)
  66. // keys = [{ name: 'foo', delimiter: '/', optional: true, repeat: true }]
  67. re.exec('/')
  68. //=> ['/', undefined]
  69. re.exec('/bar/baz')
  70. //=> ['/bar/baz', 'bar/baz']
  71. ```
  72. ##### One or more
  73. Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches. The prefix is taken into account for each match.
  74. ```js
  75. var re = pathToRegexp('/:foo+', keys)
  76. // keys = [{ name: 'foo', delimiter: '/', optional: false, repeat: true }]
  77. re.exec('/')
  78. //=> null
  79. re.exec('/bar/baz')
  80. //=> ['/bar/baz', 'bar/baz']
  81. ```
  82. #### Custom Match Parameters
  83. All parameters can be provided a custom regexp, which overrides the default (`[^\/]+`).
  84. ```js
  85. var re = pathToRegexp('/:foo(\\d+)', keys)
  86. // keys = [{ name: 'foo', ... }]
  87. re.exec('/123')
  88. //=> ['/123', '123']
  89. re.exec('/abc')
  90. //=> null
  91. ```
  92. **Please note:** Backslashes need to be escaped with another backslash in strings.
  93. #### Unnamed Parameters
  94. It is possible to write an unnamed parameter that only consists of a matching group. It works the same as a named parameter, except it will be numerically indexed.
  95. ```js
  96. var re = pathToRegexp('/:foo/(.*)', keys)
  97. // keys = [{ name: 'foo', ... }, { name: 0, ... }]
  98. re.exec('/test/route')
  99. //=> ['/test/route', 'test', 'route']
  100. ```
  101. #### Asterisk
  102. An asterisk can be used for matching everything. It is equivalent to an unnamed matching group of `(.*)`.
  103. ```js
  104. var re = pathToRegexp('/foo/*', keys)
  105. // keys = [{ name: '0', ... }]
  106. re.exec('/foo/bar/baz')
  107. //=> ['/foo/bar/baz', 'bar/baz']
  108. ```
  109. ### Parse
  110. The parse function is exposed via `pathToRegexp.parse`. This will return an array of strings and keys.
  111. ```js
  112. var tokens = pathToRegexp.parse('/route/:foo/(.*)')
  113. console.log(tokens[0])
  114. //=> "/route"
  115. console.log(tokens[1])
  116. //=> { name: 'foo', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }
  117. console.log(tokens[2])
  118. //=> { name: 0, prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '.*' }
  119. ```
  120. **Note:** This method only works with Express-style strings.
  121. ### Compile ("Reverse" Path-To-RegExp)
  122. Path-To-RegExp exposes a compile function for transforming an Express-style path into a valid path.
  123. ```js
  124. var toPath = pathToRegexp.compile('/user/:id')
  125. toPath({ id: 123 }) //=> "/user/123"
  126. toPath({ id: 'café' }) //=> "/user/caf%C3%A9"
  127. toPath({ id: '/' }) //=> "/user/%2F"
  128. toPath({ id: ':' }) //=> "/user/%3A"
  129. toPath({ id: ':' }, { pretty: true }) //=> "/user/:"
  130. var toPathRepeated = pathToRegexp.compile('/:segment+')
  131. toPathRepeated({ segment: 'foo' }) //=> "/foo"
  132. toPathRepeated({ segment: ['a', 'b', 'c'] }) //=> "/a/b/c"
  133. var toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
  134. toPathRegexp({ id: 123 }) //=> "/user/123"
  135. toPathRegexp({ id: '123' }) //=> "/user/123"
  136. toPathRegexp({ id: 'abc' }) //=> Throws `TypeError`.
  137. ```
  138. **Note:** The generated function will throw on invalid input. It will do all necessary checks to ensure the generated path is valid. This method only works with strings.
  139. ### Working with Tokens
  140. Path-To-RegExp exposes the two functions used internally that accept an array of tokens.
  141. * `pathToRegexp.tokensToRegExp(tokens, options)` Transform an array of tokens into a matching regular expression.
  142. * `pathToRegexp.tokensToFunction(tokens)` Transform an array of tokens into a path generator function.
  143. #### Token Information
  144. * `name` The name of the token (`string` for named or `number` for index)
  145. * `prefix` The prefix character for the segment (`/` or `.`)
  146. * `delimiter` The delimiter for the segment (same as prefix or `/`)
  147. * `optional` Indicates the token is optional (`boolean`)
  148. * `repeat` Indicates the token is repeated (`boolean`)
  149. * `partial` Indicates this token is a partial path segment (`boolean`)
  150. * `pattern` The RegExp used to match this token (`string`)
  151. * `asterisk` Indicates the token is an `*` match (`boolean`)
  152. ## Compatibility with Express <= 4.x
  153. Path-To-RegExp breaks compatibility with Express <= `4.x`:
  154. * No longer a direct conversion to a RegExp with sugar on top - it's a path matcher with named and unnamed matching groups
  155. * It's unlikely you previously abused this feature, it's rare and you could always use a RegExp instead
  156. * All matching RegExp special characters can be used in a matching group. E.g. `/:user(.*)`
  157. * Other RegExp features are not support - no nested matching groups, non-capturing groups or look aheads
  158. * Parameters have suffixes that augment meaning - `*`, `+` and `?`. E.g. `/:user*`
  159. ## TypeScript
  160. Includes a [`.d.ts`](index.d.ts) file for TypeScript users.
  161. ## Live Demo
  162. You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/).
  163. ## License
  164. MIT
  165. [npm-image]: https://img.shields.io/npm/v/path-to-regexp.svg?style=flat
  166. [npm-url]: https://npmjs.org/package/path-to-regexp
  167. [travis-image]: https://img.shields.io/travis/pillarjs/path-to-regexp.svg?style=flat
  168. [travis-url]: https://travis-ci.org/pillarjs/path-to-regexp
  169. [coveralls-image]: https://img.shields.io/coveralls/pillarjs/path-to-regexp.svg?style=flat
  170. [coveralls-url]: https://coveralls.io/r/pillarjs/path-to-regexp?branch=master
  171. [david-image]: http://img.shields.io/david/pillarjs/path-to-regexp.svg?style=flat
  172. [david-url]: https://david-dm.org/pillarjs/path-to-regexp
  173. [license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat
  174. [license-url]: LICENSE.md
  175. [downloads-image]: http://img.shields.io/npm/dm/path-to-regexp.svg?style=flat
  176. [downloads-url]: https://npmjs.org/package/path-to-regexp