Skip to the solution
MediumFrontend6 min read

Build a Simple Client-Side Router That Matches Path Patterns

386 views

The problem

Problem, as an interviewer would state it: "Build a simple client-side router: given a list of { pattern, handler } routes (supporting dynamic segments like :id and a wildcard *), match a real path against them and extract any named parameters."

Examples:

Code
router.match("/users/42"); // { handler: "userDetail", params: { id: "42" } }
router.match("/users/42/posts/7"); // { handler: "userPost", params: { id: "42", postId: "7" } }

Clarifying questions expected:

  • What should a route with MULTIPLE dynamic segments (like /users/:id/posts/:postId) look like once matched?
  • Should routes be checked in ARRAY ORDER, with the first match winning, or should more "specific" routes always take precedence regardless of order?
  • Does a wildcard * segment need to capture the matched remainder as a param too, or just match anything?

Code / implementation expected: Yes — real, direct proof matching a single dynamic segment, multiple dynamic segments, a static route, a wildcard, and a genuinely unmatched path.

  • routing
  • spa
  • pattern-matching

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the router correctly matches single and multiple dynamic segments, a static route, a wildcard, and returns null for an unmatched path

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 116 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement a Debounced Search Input With Race-Condition-Safe Request Cancellation

Continue