gitmyhub

path-to-regexp

TypeScript ★ 2 updated 10y ago ⑂ fork

Express-style path to regexp

A TypeScript library that turns route patterns like /user/:id into regular expressions for URL matching, and can also build URLs back from parameter values.

TypeScriptsetup: easycomplexity 2/5

Plain-English Explanation: path-to-regexp

This library solves a specific problem: converting human-readable web route patterns (like the ones you write in Express.js) into patterns a computer can match against. If you've ever built a web app and written routes like /user/:name or /posts/:id, this tool is what makes those work behind the scenes.

Here's what it does in practice. You give it a route pattern as a string—say /api/users/:userId/posts/:postId—and it transforms that into a regular expression that can recognize which URLs match that pattern. It also extracts the variable parts (the ones starting with a colon) so your code knows what values were actually provided. For example, if someone visits /api/users/42/posts/789, the tool tells you that userId is 42 and postId is 789. It also supports variations like optional parameters (:name?), repeating segments (:tags+), and custom matching rules (:id(\\d+) for digits only).

The library also works in reverse: you can give it concrete values and it generates the correct URL string. So if you have { userId: 42, postId: 789 }, it can build /api/users/42/posts/789 for you. This is useful for link generation in templates or redirects.

Web framework developers and routing libraries use this under the hood, but it's also useful if you're building your own routing system or need flexible URL matching. The README includes detailed examples for optional parameters, repeating segments, custom regex patterns, and more advanced features. It's written in TypeScript and includes type definitions, so if you're using TypeScript in your project, you get full autocomplete support. The code handles a lot of edge cases around slashes, special characters, and parameter validation so you don't have to think about them yourself.

Where it fits