URL path pattern matching and parameter extraction
npm install @philiprehberger/path-patternURL path pattern matching and parameter extraction
npm install @philiprehberger/path-pattern
import { match, compile, test, rank, toRegex } from '@philiprehberger/path-pattern';
// Match a path and extract parameters
const result = match('/users/:id/posts/:postId', '/users/42/posts/7');
// { params: { id: '42', postId: '7' }, path: '/users/42/posts/7', pattern: '/users/:id/posts/:postId' }
// Wildcard matching
match('/files/*path', '/files/docs/readme.md');
// { params: { path: 'docs/readme.md' }, ... }
// Compile a pattern with parameters
compile('/users/:id', { id: '42' });
// '/users/42'
// Test if a path matches
test('/users/:id', '/users/42'); // true
test('/users/:id', '/posts/42'); // false
// Rank patterns by specificity
rank(['/users/*', '/users/:id', '/users/admin']);
// ['/users/admin', '/users/:id', '/users/*']
// Convert a pattern to a RegExp
const re = toRegex('/users/:id');
'/users/42'.match(re); // groups: { id: '42' }
match(pattern, path)Matches a URL path against a pattern and extracts named parameters and wildcards.
string - Pattern with :param and *wildcard segmentsstring - The URL path to matchMatchResult | null - Match result with params, path, and pattern, or nullcompile(pattern, params?, options?)Compiles a pattern by substituting parameter values into it.
string - The pattern to compileRecord<string, string> - Parameter values to substituteboolean - Whether to encode URI components (default: true)string - The compiled pathError if a required parameter is missingtest(pattern, path)Tests whether a path matches a pattern without extracting parameters.
string - The pattern to test againststring - The URL path to testbooleanrank(patterns)Sorts an array of patterns by specificity, from most specific to least specific. Static segments rank highest, then named parameters, then wildcards.
string[] - Patterns to rankstring[] - New sorted arraytoRegex(pattern)Converts a pattern into a RegExp with named capture groups.
string - The pattern to convertRegExpnpm install
npm run build
npm run typecheck
npm test
If you find this project useful: