Blog>
Snippets

Multi-Segment Path Matcher

Showcase the creation of a custom route matcher that can handle multi-segment paths with different matching criteria for each segment.
function pathMatcher(routePattern, path) {
  const routeParts = routePattern.split('/').filter(Boolean);
  const pathParts = path.split('/').filter(Boolean);

  if (routeParts.length !== pathParts.length) return false;

  for (let i = 0; i < routeParts.length; i++) {
    // For variable segments, do a custom match here
    if (routeParts[i].startsWith(':')) continue;

    // Exact match for non-variable segments
    if (routeParts[i] !== pathParts[i]) return false;
  }

  return true;
}
Creates a function 'pathMatcher' which takes a route pattern and a test path, compares their segments and determines if they match. Variable segments in the pattern start with ':' and are ignored for matching, allowing any value in the test path.
const routes = [
  { pattern: '/users/:userId/posts/:postId', handler: () => console.log('User post') },
  { pattern: '/users/:userId', handler: () => console.log('User profile') }
];

function handlePath(path) {
  for (const route of routes) {
    if (pathMatcher(route.pattern, path)) {
      route.handler();
      return;
    }
  }
  console.log('No route matched');
}
Defines an array of route objects with pattern and handler keys, and a function 'handlePath' to execute the handler for the first route matching the given path. If no route matches, logs 'No route matched'.
handlePath('/users/123'); // Logs 'User profile'
handlePath('/users/123/posts/456'); // Logs 'User post'
handlePath('/invalid/path'); // Logs 'No route matched'
Executes the handlePath function with different paths to demonstrate matching against defined routes.