gitmyhub

path-to-regexp

TypeScript ★ 8.6k updated 20d ago

Turn a path string such as `/user/:name` into a regular expression

A small JavaScript library that converts URL path patterns like /user/:name into regular expressions for matching URLs and extracting named parameters, used internally by Express.js and other Node routers.

TypeScriptJavaScriptNode.jssetup: easycomplexity 2/5

Path-to-RegExp is a small JavaScript library that takes a URL path pattern, like /user/:name, and turns it into a regular expression that can test whether an actual URL matches that pattern, and if so, pull out the named parts. For example, if you define a route as /user/:name, this library can tell you that /user/alice matches and that the name value is alice. This kind of matching is the core mechanism behind how web frameworks know which function to run when someone visits a particular URL.

The library provides a few related tools. The match function lets you check whether a real path fits your pattern and gives you back the captured values. The compile function does the reverse: you give it a pattern and some values, and it builds a valid URL from them, handling encoding of special characters automatically. There is also a parse function that breaks a pattern down into tokens for cases where you need to work with the structure more directly.

Path patterns support several features described in the README. Named parameters (prefixed with a colon, like :id) capture the value at that position in the URL. Wildcard parameters (prefixed with an asterisk, like *splat) match across multiple path segments. Optional sections can be wrapped in braces, so /users{/:id}/delete matches both /users/delete and /users/123/delete.

This library is closely connected to the Express.js web framework and other Node.js routers, which use it internally to handle routing. The current version breaks compatibility with Express 4.x and earlier in a few ways, and the README documents those differences along with error messages you might see if you are upgrading from an older version.

The project is published on npm as path-to-regexp and is released under the MIT license.

Where it fits