Tiny Route Pattern to RegExp Utility
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
-
TypeError: regexparam is not a function
cause Attempting to call `require('regexparam')()` directly in CommonJS after v2.0.0, where the default export was removed.fixChange your CommonJS import and usage from `const regexparam = require('regexparam'); regexparam('/path')` to `const { parse } = require('regexparam'); parse('/path')`. -
SyntaxError: The requested module 'regexparam' does not provide an export named 'parse'
cause Using `import { parse } from 'regexparam'` with a version prior to v2.0.0, where `parse` was not a named export but the default export.fixEither update `regexparam` to v2.0.0 or later, or change your import to `import regexparam from 'regexparam'` and use `regexparam('/path')`. -
Route with optional wildcard /users/*? matches incorrectly.
cause Behavioral change in optional wildcard matching between v2.x and v3.x of `regexparam`.fixUpgrade to `regexparam` v3.0.0 and thoroughly test routes using optional wildcards (`*?`) to confirm expected matching behavior.
Warnings
- breaking The behavior of optional wildcard patterns (e.g., `/books/*?`) has been corrected in v3.0.0. Previously, the optional part was ignored, making them behave like regular wildcards. This fix changes the generated `RegExp` and thus the matching behavior for these patterns.
- breaking The default export of the library was converted to a named `parse` export in v2.0.0. This means the import method for the primary parsing function has changed.
- breaking Version 2.0.0 increased the minimum required Node.js runtime from 6.x to 8.x.
- gotcha When matching or testing against a generated `RegExp` pattern, the input path string MUST begin with a leading slash (`/`). Paths without a leading slash will not match correctly.
- gotcha The `inject` function will leave non-optional parameter placeholders in the output string if the corresponding value is not provided in the parameters object.
Install
-
npm install regexparam -
yarn add regexparam -
pnpm add regexparam
Imports
- parse
import regexparam from 'regexparam'
import { parse } from 'regexparam' - inject
const inject = require('regexparam').injectimport { inject } from 'regexparam' - Result type
import type { Result } from 'regexparam'
Quickstart
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