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.
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.
Input: pattern = "/users/:id", path = "/users/42/settings" Output: null
The path has an extra segment.
1 to 200 characters.% escapes in paths are valid.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).
I'm here to help with #735 Match a Route Pattern. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.