Blog>
Snippets

Parameterized Path Matcher

Demonstrate the creation of a custom route matcher that accepts parameters within the path, such as an ID.
function pathMatch(pattern, pathname) {
  const patternParts = pattern.split('/').filter(Boolean);
  const pathParts = pathname.split('/').filter(Boolean);
  const params = {};

  if (patternParts.length !== pathParts.length) return null;

  for (let i = 0; i < patternParts.length; i++) {
    if (patternParts[i].startsWith(':')) {
      const paramName = patternParts[i].substring(1);
      params[paramName] = pathParts[i];
    } else if (patternParts[i] !== pathParts[i]) {
      return null;
    }
  }

  return params;
}
Defines a function 'pathMatch' that takes a pattern with parameters and a pathname. It splits the pattern and the pathname into parts, compares them, and collects parameters where the pattern has placeholders (e.g., :id). If there's a match, it returns an object with the parameters; if not, it returns null.
const routePattern = '/users/:userId/posts/:postId';
const currentPath = '/users/123/posts/456';
const matchParams = pathMatch(routePattern, currentPath);

if (matchParams) {
  console.log('Matched with parameters:', matchParams);
} else {
  console.log('No match found.');
}
Creates an example route pattern with parameters and a current path to be matched. Then calls the 'pathMatch' function with these arguments, and logs the result to the console. It logs the matched parameters if there's a match, otherwise informs no match was found.