Skip to the code
cf.
+10 XP

#735 Match a Route Pattern

easy

Write the core of a client-side router. matchRoute(pattern, path) checks whether a URL path fits a route pattern and returns the captured parameters as an object, or null if it doesn't fit.

Split both on / and ignore empty pieces, so leading, trailing, and doubled slashes don't matter. Compare segment by segment: a plain segment must be equal; a segment :name matches any one segment and stores it under name, decoded with decodeURIComponent; a * (only ever the last segment of a pattern) matches all remaining segments, even none, and stores them joined by / under "*". Without a *, both must have the same number of segments.

Example 1

Input: pattern = "/users/:id/posts/:postId", path = "/users/42/posts/7"
Output: {"id":"42","postId":"7"}

Plain segments match and the two parameters are captured.

Example 2

Input: pattern = "/users/:id", path = "/users/42/settings"
Output: null

The path has an extra segment.

Constraints

  • Patterns and paths are 1 to 200 characters.
  • All % escapes in paths are valid.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).