Research
Security News
Kill Switch Hidden in npm Packages Typosquatting Chalk and Chokidar
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
regexparam
Advanced tools
A tiny (399B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇
The regexparam npm package is a utility for matching URL patterns using regular expressions. It is designed to be lightweight and efficient, making it suitable for routing in web applications.
Basic Pattern Matching
This feature allows you to define URL patterns with named parameters. The `parse` function converts the pattern into a regular expression and extracts parameter names.
const { parse } = require('regexparam');
const result = parse('/user/:id');
console.log(result);
Matching URLs
This feature allows you to match a URL against a predefined pattern. The `match` function returns an object with the matched parameters if the URL matches the pattern.
const { match } = require('regexparam');
const pattern = parse('/user/:id');
const result = match('/user/123', pattern);
console.log(result);
Optional Parameters
This feature allows you to define optional parameters in your URL patterns. The `parse` function can handle patterns with optional parameters, and the `match` function will correctly match URLs with or without the optional parameter.
const { parse, match } = require('regexparam');
const pattern = parse('/user/:id?');
const result1 = match('/user/123', pattern);
const result2 = match('/user', pattern);
console.log(result1, result2);
The path-to-regexp package is a popular utility for converting URL patterns into regular expressions. It offers similar functionality to regexparam but is more feature-rich and widely used in the community. It supports advanced pattern matching, including custom parameter types and modifiers.
The route-parser package provides a similar capability to regexparam, allowing you to define and match URL patterns. It is designed to be simple and easy to use, with a focus on readability and maintainability of route definitions.
The url-pattern package is another alternative for matching URL patterns. It offers a straightforward API for defining and matching patterns, with support for named parameters and wildcards. It is less feature-rich compared to path-to-regexp but provides a simpler interface.
A tiny (399B) utility that converts route patterns into RegExp. Limited alternative to
path-to-regexp
🙇
With regexparam
, you may turn a pathing string (eg, /users/:id
) into a regular expression.
An object with shape of { keys, pattern }
is returned, where pattern
is the RegExp
and keys
is an array of your parameter name(s) in the order that they appeared.
Unlike path-to-regexp
, this module does not create a keys
dictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Similarly, and most importantly, regexparam
only handles basic pathing operators:
/foo
, /foo/bar
)/:title
, /books/:title
, /books/:genre/:title
)/movies/:title.mp4
, /movies/:title.(mp4|mov)
)/:title?
, /books/:title?
, /books/:genre/:title?
)*
, /books/*
, /books/:genre/*
)/books/*?
)This module exposes three module definitions:
dist/index.js
dist/index.mjs
dist/index.min.js
$ npm install --save regexparam
import { parse, inject } from 'regexparam';
// Example param-assignment
function exec(path, result) {
let i=0, out={};
let matches = result.pattern.exec(path);
while (i < result.keys.length) {
out[ result.keys[i] ] = matches[++i] || null;
}
return out;
}
// Parameter, with Optional Parameter
// ---
let foo = parse('/books/:genre/:title?')
// foo.pattern => /^\/books\/([^\/]+?)(?:\/([^\/]+?))?\/?$/i
// foo.keys => ['genre', 'title']
foo.pattern.test('/books/horror'); //=> true
foo.pattern.test('/books/horror/goosebumps'); //=> true
exec('/books/horror', foo);
//=> { genre: 'horror', title: null }
exec('/books/horror/goosebumps', foo);
//=> { genre: 'horror', title: 'goosebumps' }
// Parameter, with suffix
// ---
let bar = parse('/movies/:title.(mp4|mov)');
// bar.pattern => /^\/movies\/([^\/]+?)\.(mp4|mov)\/?$/i
// bar.keys => ['title']
bar.pattern.test('/movies/narnia'); //=> false
bar.pattern.test('/movies/narnia.mp3'); //=> false
bar.pattern.test('/movies/narnia.mp4'); //=> true
exec('/movies/narnia.mp4', bar);
//=> { title: 'narnia' }
// Wildcard
// ---
let baz = parse('users/*');
// baz.pattern => /^\/users\/(.*)\/?$/i
// baz.keys => ['*']
baz.pattern.test('/users'); //=> false
baz.pattern.test('/users/lukeed'); //=> true
baz.pattern.test('/users/'); //=> true
// Optional Wildcard
// ---
let baz = parse('/users/*?');
// baz.pattern => /^\/users(?:\/(.*))?(?=$|\/)/i
// baz.keys => ['*']
baz.pattern.test('/users'); //=> true
baz.pattern.test('/users/lukeed'); //=> true
baz.pattern.test('/users/'); //=> true
// Injecting
// ---
inject('/users/:id', {
id: 'lukeed'
}); //=> '/users/lukeed'
inject('/movies/:title.mp4', {
title: 'narnia'
}); //=> '/movies/narnia.mp4'
inject('/:foo/:bar?/:baz?', {
foo: 'aaa'
}); //=> '/aaa'
inject('/:foo/:bar?/:baz?', {
foo: 'aaa',
baz: 'ccc'
}); //=> '/aaa/ccc'
inject('/posts/:slug/*', {
slug: 'hello',
}); //=> '/posts/hello'
inject('/posts/:slug/*', {
slug: 'hello',
'*': 'x/y/z',
}); //=> '/posts/hello/x/y/z'
// Missing non-optional value
// ~> keeps the pattern in output
inject('/hello/:world', {
abc: 123
}); //=> '/hello/:world'
Important: When matching/testing against a generated RegExp, your path must begin with a leading slash (
"/"
)!
For fine-tuned control, you may pass a RegExp
value directly to regexparam
as its only parameter.
In these situations, regexparam
does not parse nor manipulate your pattern in any way! Because of this, regexparam
has no "insight" on your route, and instead trusts your input fully. In code, this means that the return value's keys
is always equal to false
and the pattern
is identical to your input value.
This also means that you must manage and parse your own keys
~!
You may use named capture groups or traverse the matched segments manually the "old-fashioned" way:
Important: Please check your target browsers' and target Node.js runtimes' support!
// Named capture group
const named = regexparam.parse(/^\/posts[/](?<year>[0-9]{4})[/](?<month>[0-9]{2})[/](?<title>[^\/]+)/i);
const { groups } = named.pattern.exec('/posts/2019/05/hello-world');
console.log(groups);
//=> { year: '2019', month: '05', title: 'hello-world' }
// Widely supported / "Old-fashioned"
const named = regexparam.parse(/^\/posts[/]([0-9]{4})[/]([0-9]{2})[/]([^\/]+)/i);
const [url, year, month, title] = named.pattern.exec('/posts/2019/05/hello-world');
console.log(year, month, title);
//=> 2019 05 hello-world
Returns: Object
Parse a route pattern into an equivalent RegExp pattern. Also collects the names of pattern's parameters as a keys
array. An input
that's already a RegExp is kept as is, and regexparam
makes no additional insights.
Returns a { keys, pattern }
object, where pattern
is always a RegExp
instance and keys
is either false
or a list of extracted parameter names.
Important: The
keys
will always befalse
wheninput
is a RegExp and it will always be an Array wheninput
is a string.
Type: string
or RegExp
When input
is a string, it's treated as a route pattern and an equivalent RegExp is generated.
Note: It does not matter if
input
strings begin with a/
— it will be added if missing.
When input
is a RegExp, it will be used as is – no modifications will be made.
Type: boolean
Default: false
Should the RegExp
match URLs that are longer than the str
pattern itself?
By default, the generated RegExp
will test that the URL begins and ends with the pattern.
Important: When
input
is a RegExp, theloose
argument is ignored!
const { parse } = require('regexparam');
parse('/users').pattern.test('/users/lukeed'); //=> false
parse('/users', true).pattern.test('/users/lukeed'); //=> true
parse('/users/:name').pattern.test('/users/lukeed/repos'); //=> false
parse('/users/:name', true).pattern.test('/users/lukeed/repos'); //=> true
Returns: string
Returns a new string by replacing the pattern
segments/parameters with their matching values.
Important: Named segments (eg,
/:name
) that do not have avalues
match will be kept in the output. This is true except for optional segments (eg,/:name?
) and wildcard segments (eg,/*
).
Type: string
The route pattern that to receive injections.
Type: Record<string, string>
The values to be injected. The keys within values
must match the pattern
's segments in order to be replaced.
Note: To replace a wildcard segment (eg,
/*
), define avalues['*']
key.
As of version 1.3.0
, you may use regexparam
with Deno. These options are all valid:
// The official Deno registry:
import regexparam from 'https://deno.land/x/regexparam/src/index.js';
// Third-party CDNs with ESM support:
import regexparam from 'https://cdn.skypack.dev/regexparam';
import regexparam from 'https://esm.sh/regexparam';
Note: All registries support versioned URLs, if desired.
The above examples always resolve to the latest published version.
RegExp
s.MIT © Luke Edwards
FAQs
A tiny (399B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇
The npm package regexparam receives a total of 362,385 weekly downloads. As such, regexparam popularity was classified as popular.
We found that regexparam demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers found several malicious npm packages typosquatting Chalk and Chokidar, targeting Node.js developers with kill switches and data theft.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.