Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

URL router with path parameters in JavaScript

91 A router that matches paths and captures parameters

fair

Match a URL against a list of patterns like /vendors/:id/orders/:orderId and return which route matched plus the captured parameters. Handle a trailing slash, a percent-encoded segment, a query string, a *rest wildcard that swallows everything left, and a URL that matches nothing. Then show why a static route has to be declared before the dynamic one that would also match it.

Stuck? Three hints, smallest first
  1. 1. Split both the pattern and the path on / and drop the empty pieces with filter(Boolean).
  2. 2. A segment starting with : captures; anything else must match exactly.
  3. 3. First match wins, so the order of the route list is part of its meaning.

The answer

function createRouter(routes) {
  const compiled = routes.map((route) => ({ ...route, parts: route.path.split('/').filter(Boolean) }));

  const matchParts = (parts, segments) => {
    const params = {};
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      if (part.startsWith('*')) {                       // swallow the remainder, slashes and all
        params[part.slice(1)] = segments.slice(i).map(decodeURIComponent).join('/');
        return params;
      }
      if (i >= segments.length) return null;            // pattern longer than the path
      if (part.startsWith(':')) {
        params[part.slice(1)] = decodeURIComponent(segments[i]);
        continue;
      }
      if (part !== segments[i]) return null;
    }
    return parts.length === segments.length ? params : null;
  };

  return function match(url) {
    const [pathname, search = ''] = url.split('?');
    const segments = pathname.split('/').filter(Boolean);
    for (const route of compiled) {
      const params = matchParts(route.parts, segments);
      if (params !== null) return { name: route.name, params, search };
    }
    return null;
  };
}

const match = createRouter([
  { name: 'home', path: '/' },
  { name: 'newVendor', path: '/vendors/new' },        // must come before /vendors/:id
  { name: 'vendor', path: '/vendors/:id' },
  { name: 'vendorOrder', path: '/vendors/:id/orders/:orderId' },
  { name: 'files', path: '/files/*rest' },
]);

const root = match('/');
const one = match('/vendors/42');
const trailingSlash = match('/vendors/42/');
const staticWins = match('/vendors/new');
const encoded = match('/vendors/Adaeze%20Fabrics');
const nested = match('/vendors/42/orders/ORD-001');
const withQuery = match('/vendors/42?tab=orders&page=2');
const unmatched = match('/nothing/here');
const wildcard = match('/files/2025/lagos/invoice%20final.pdf');

console.log('/vendors/42            :', one.name, one.params);
console.log('/vendors/new           :', staticWins.name, '<- static route declared first');
console.log('/vendors/42?tab=orders :', withQuery.params, 'search:', withQuery.search);
console.log('/files/...             :', wildcard.params);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the root matches with no parameters', root, { name: 'home', params: {}, search: '' });
test('a :segment is captured under its name, trailing slash or not', [one.name, one.params, trailingSlash.params], ['vendor', { id: '42' }, { id: '42' }]);
test('the static route wins because it is declared first, so /vendors/new is not an id', [staticWins.name, staticWins.params], ['newVendor', {}]);
test('captured segments are percent-decoded', encoded.params, { id: 'Adaeze Fabrics' });
test('two parameters in one pattern', [nested.name, nested.params], ['vendorOrder', { id: '42', orderId: 'ORD-001' }]);
test('the query string plays no part in matching and comes back separately', [withQuery.name, withQuery.params, withQuery.search], ['vendor', { id: '42' }, 'tab=orders&page=2']);
test('nothing matching gives null, which is the caller\'s 404, not a throw', unmatched, null);
test('a *wildcard takes everything left, slashes included, still decoded', wildcard.params, { rest: '2025/lagos/invoice final.pdf' });

Two lines carry the whole matcher. filter(Boolean) after the split is what makes /vendors/42 and /vendors/42/ the same route and stops the leading slash producing a phantom empty segment. And the final parts.length === segments.length check is what stops /vendors/:id matching /vendors/42/orders/1 — without it, a short pattern quietly swallows every longer path beneath it.

The third assertion is the ordering rule, and it is the one that bites in real apps. /vendors/new and /vendors/:id both match the same URL, so the list order decides, and putting the dynamic route first gives you a vendor page for the id "new". Real routers avoid the trap by ranking specificity — static beats dynamic beats wildcard — rather than trusting declaration order. Knowing which of the two your router does is the difference between a working form and a mystifying 404.

Decoding belongs in the matcher, not in the page. /vendors/Adaeze%20Fabrics arrives encoded, and a page that renders the raw segment shows the percent sign to the user. Decode once, where the capture happens, and note that a segment containing an encoded slash — %2F — becomes a slash after decoding, which is exactly why the split happens first and the decode second.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.