Match a Route Pattern
Medium · Routing
Frameworks like Express turn a route such as /users/:id into req.params. Write matchRoute(pattern, path) that returns the params object, or null if the path does not match.
- Split both on /. They must have the same number of segments.
- A pattern segment starting with : is a parameter: it matches any NON-empty segment, and its value is URL-decoded with decodeURIComponent.
- Other segments must match exactly, and case matters (Express ignores case by default, but we do not).
- One trailing slash on the path is tolerated (/users/7/ matches /users/:id), but not two.
Next: path.posix.normalize