Tiny Route Pattern to RegExp Utility

3.0.0 · active · verified Tue Apr 21

regexparam is a minimalist (399B) utility designed to convert URL-like route patterns (e.g., `/users/:id`) into JavaScript `RegExp` objects, extracting parameter keys in the process. It serves as a more lightweight and focused alternative to libraries like `path-to-regexp`. The current stable version is `3.0.0`. Releases occur periodically, addressing bug fixes and introducing minor breaking changes, typically every few months for major versions. Key differentiators include its extremely small footprint and its specific focus on basic routing patterns: static, parameter (with or without suffixes), optional parameters, wildcards, and optional wildcards. Unlike more comprehensive routing solutions, regexparam only handles parsing string patterns and does not manage a `keys` dictionary directly or mutate variables. It ships with CommonJS, ESModule, and UMD formats and includes TypeScript type definitions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse a route pattern into a RegExp and keys, test paths against it, extract parameters, and inject parameters into a route string using `parse` and `inject`.

import { parse, inject } from 'regexparam';

// A helper function to extract parameters from a matched path
function exec(path: string, result: ReturnType<typeof parse>): Record<string, string | null> {
  let i = 0;
  const out: Record<string, string | null> = {};
  const matches = result.pattern.exec(path);

  if (!matches) {
    return {}; // No match
  }

  while (i < result.keys.length) {
    // Matches array index starts from 1 for captured groups
    out[result.keys[i]] = matches[++i] || null;
  }
  return out;
}

// Example 1: Parsing a route with optional parameters
const route1 = parse('/books/:genre/:title?');
console.log('Route 1 pattern:', route1.pattern.source);
console.log('Route 1 keys:', route1.keys);

const path1a = '/books/horror';
console.log(`Matching "${path1a}":`, route1.pattern.test(path1a));
console.log(`Extracted params for "${path1a}":`, exec(path1a, route1));

const path1b = '/books/science-fiction/dune';
console.log(`Matching "${path1b}":`, route1.pattern.test(path1b));
console.log(`Extracted params for "${path1b}":`, exec(path1b, route1));

// Example 2: Injecting parameters into a route
const injectedPath1 = inject('/users/:id', { id: 'alice' });
console.log('Injected path (user alice):', injectedPath1);

const injectedPath2 = inject('/posts/:slug/*', { slug: 'my-post', '*': 'comments/123' });
console.log('Injected path (post with wildcard):', injectedPath2);

// Example 3: Handling missing non-optional parameters during injection
const incompleteInjection = inject('/products/:category/:item', { category: 'electronics' });
console.log('Incomplete injection:', incompleteInjection); // Missing 'item' parameter

view raw JSON →