@prexjs/path-to-regexp
v1.0.0
Published
Turn path strings like /user/:name into regular expressions and reverse-compile paths from parameters.
Readme
@prexjs/path-to-regexp
Turn path strings like /user/:name into regular expressions and reverse-compile paths from parameters.
@prexjs/path-to-regexp compiles route patterns like /user/:name and /files/*path into Regular Expressions for URL matching, and supports bi-directional reverse path compilation with parameters.
Features
- Named parameters (
:id,:username). - Wildcard parameters (
*splat). - Optional groups (
{/optional}). - Reverse compilation from param data back to URL strings (
compile()). - Pattern matching helper returning parsed param records (
match()). - Dual ES Module (
.mjs) and CommonJS (.cjs) support with TypeScript definitions. - Zero runtime dependencies.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/path-to-regexp
# pnpm
pnpm add @prexjs/path-to-regexp
# Yarn
yarn add @prexjs/path-to-regexp
# Bun
bun add @prexjs/path-to-regexpQuick start
import { pathToRegexp, match, compile } from '@prexjs/path-to-regexp';
// 1. Regular expression generation
const { regexp, keys } = pathToRegexp('/user/:id');
console.log(regexp.test('/user/42')); // true
// 2. Matching paths
const matcher = match('/posts/:category/:slug');
const result = matcher('/posts/news/launch-day');
if (result) {
console.log(result.params);
// { category: 'news', slug: 'launch-day' }
}
// 3. Compiling back to URL
const toPath = compile('/posts/:category/:slug');
console.log(toPath({ category: 'tech', slug: 'typescript-5' }));
// '/posts/tech/typescript-5'Both default and named exports are supported:
import {
pathToRegexp,
match,
compile,
parse,
stringify,
TokenData,
PathError,
type MatchFunction,
type PathFunction,
} from '@prexjs/path-to-regexp';Compatibility
@prexjs/path-to-regexp is designed for JavaScript and TypeScript projects running on Node.js, Deno, Bun, or browsers.
License
This project is licensed under the MIT License. See LICENSE for the full license text.
Related projects
- prex.js — prex.js monorepo and ecosystem.
