Skip to the code
cf.
+10 XP

#736 Fill In a Route

easy

Links in a single-page app are built from route patterns, like /users/:id/posts/:postId with { id: 42, postId: "a b" } giving /users/42/posts/a%20b.

Write buildPath(pattern, params). Split the pattern on / and ignore empty pieces. Keep plain segments as they are, and replace each :name segment with encodeURIComponent(String(params[name])). Join the segments with / and put a / in front; a pattern with no segments gives "/". If any parameter is missing from params, return null. Extra entries in params are ignored.

Example 1

Input: pattern = "/users/:id/posts/:postId", params = {"id":42,"postId":"a b"}
Output: "/users/42/posts/a%20b"

The number is turned into text and the space is encoded.

Example 2

Input: pattern = "/users/:id", params = {}
Output: null

id is missing.

Constraints

  • Patterns are 1 to 200 characters and contain no *.
  • Parameter values are strings or numbers.
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).