Top Related Projects
a glob matcher in javascript
glob functionality for node.js
Highly optimized wildcard and glob matching library. Faster, drop-in replacement to minimatch and multimatch. Used by square, webpack, babel core, yarn, jest, ract-native, taro, bulma, browser-sync, stylelint, nyc, ava, and many others! Follow micromatch's author: https://github.com/jonschlinkert
Quick Overview
Path-to-RegExp is a JavaScript library that converts Express-style path strings (like /user/:id
) into regular expressions. It's widely used in routing libraries and frameworks to match URLs and extract parameters from them. The library is lightweight, flexible, and supports various path matching patterns.
Pros
- Highly flexible, supporting a wide range of path matching patterns
- Excellent performance due to efficient regular expression generation
- Well-maintained and widely adopted in the JavaScript ecosystem
- Supports both Node.js and browser environments
Cons
- Learning curve for complex path patterns
- Regular expressions can be hard to debug for inexperienced developers
- Limited built-in support for handling query parameters
Code Examples
- Basic path matching:
import { pathToRegexp } from 'path-to-regexp';
const regexp = pathToRegexp('/user/:id');
console.log(regexp.test('/user/123')); // true
console.log(regexp.test('/user/abc')); // true
console.log(regexp.test('/user')); // false
- Extracting parameters:
import { match } from 'path-to-regexp';
const matchFn = match('/user/:id');
const result = matchFn('/user/456');
console.log(result.params); // { id: '456' }
- Creating a URL from a path pattern:
import { compile } from 'path-to-regexp';
const toPath = compile('/user/:id');
const path = toPath({ id: 789 });
console.log(path); // '/user/789'
Getting Started
To use Path-to-RegExp in your project, first install it via npm:
npm install path-to-regexp
Then, import and use the functions in your JavaScript code:
import { pathToRegexp, match, compile } from 'path-to-regexp';
// Create a regular expression
const regexp = pathToRegexp('/user/:id');
// Match a path and extract parameters
const matchFn = match('/user/:id');
const result = matchFn('/user/123');
// Generate a path from a pattern
const toPath = compile('/user/:id');
const path = toPath({ id: 456 });
This library is versatile and can be used in various scenarios where URL path matching and manipulation are required.
Competitor Comparisons
a glob matcher in javascript
Pros of minimatch
- Simpler syntax for basic glob patterns
- Built-in support for common glob features like negation and extglobs
- Lightweight and focused on file path matching
Cons of minimatch
- Less flexible for complex URL routing patterns
- Limited support for capturing groups and named parameters
- May require additional libraries for advanced use cases
Code Comparison
minimatch:
const minimatch = require('minimatch');
minimatch('file.txt', '*.txt'); // true
minimatch('path/to/file.js', '**/*.js'); // true
path-to-regexp:
const pathToRegexp = require('path-to-regexp');
const keys = [];
const regex = pathToRegexp('/user/:id', keys);
regex.test('/user/123'); // true
Summary
minimatch is better suited for file path matching and simple glob patterns, while path-to-regexp excels in URL routing and complex path matching scenarios. minimatch offers a more straightforward API for basic use cases, but path-to-regexp provides greater flexibility for advanced routing needs.
Choose minimatch for:
- File system operations
- Simple wildcard matching
- Lightweight glob pattern matching
Choose path-to-regexp for:
- URL routing in web applications
- Complex path matching with parameters
- Generating URLs from route patterns
Both libraries have their strengths, and the choice depends on the specific requirements of your project.
glob functionality for node.js
Pros of node-glob
- More powerful for file system operations, supporting complex globbing patterns
- Built-in support for handling directories and file system traversal
- Widely used in many Node.js projects, especially for build tools and task runners
Cons of node-glob
- Slower performance for simple pattern matching compared to path-to-regexp
- Limited to file system operations, not suitable for general-purpose string matching
- More complex API and usage for basic pattern matching scenarios
Code Comparison
node-glob:
const glob = require('glob');
glob('**/*.js', (err, files) => {
console.log(files);
});
path-to-regexp:
const { pathToRegexp } = require('path-to-regexp');
const regexp = pathToRegexp('/user/:id');
console.log(regexp.test('/user/123'));
Summary
node-glob is better suited for file system operations and complex globbing patterns, while path-to-regexp excels in URL routing and simple string pattern matching. node-glob offers more powerful features for working with directories and file traversal, but may be overkill for basic pattern matching. path-to-regexp provides a simpler API and better performance for URL-like patterns, but lacks the file system capabilities of node-glob. Choose the library based on your specific use case: file system operations (node-glob) or URL routing and simple pattern matching (path-to-regexp).
Highly optimized wildcard and glob matching library. Faster, drop-in replacement to minimatch and multimatch. Used by square, webpack, babel core, yarn, jest, ract-native, taro, bulma, browser-sync, stylelint, nyc, ava, and many others! Follow micromatch's author: https://github.com/jonschlinkert
Pros of micromatch
- More powerful and flexible pattern matching capabilities
- Supports advanced globbing features like brace expansion and extglobs
- Faster performance for complex patterns and large sets of files
Cons of micromatch
- Larger package size and more dependencies
- Steeper learning curve due to more advanced features
- May be overkill for simple path matching use cases
Code comparison
micromatch:
const micromatch = require('micromatch');
micromatch(['foo.js', 'bar.js'], '*.js');
// => ['foo.js', 'bar.js']
micromatch(['foo.js', 'bar.js'], '!*.js');
// => []
path-to-regexp:
const pathToRegexp = require('path-to-regexp');
const keys = [];
const regexp = pathToRegexp('/foo/:bar', keys);
regexp.exec('/foo/hello');
// => ['/foo/hello', 'hello']
Key differences
- micromatch is designed for glob pattern matching and file system operations
- path-to-regexp focuses on converting URL path patterns to regular expressions
- micromatch offers more extensive pattern matching capabilities
- path-to-regexp is more suitable for routing in web applications
Use cases
- Choose micromatch for file system operations, glob matching, and complex pattern matching scenarios
- Opt for path-to-regexp when working with URL routing and simple path matching in web applications
Both libraries have their strengths, and the choice depends on the specific requirements of your project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Path-to-RegExp
Turn a path string such as
/user/:name
into a regular expression.
Installation
npm install path-to-regexp --save
Usage
const {
match,
pathToRegexp,
compile,
parse,
stringify,
} = require("path-to-regexp");
Parameters
Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo
). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name"
).
const fn = match("/:foo/:bar");
fn("/test/route");
//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }
Wildcard
Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo
).
const fn = match("/*splat");
fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }
Optional
Braces can be used to define parts of the path that are optional.
const fn = match("/users{/:id}/delete");
fn("/users/delete");
//=> { path: '/users/delete', params: {} }
fn("/users/123/delete");
//=> { path: '/users/123/delete', params: { id: '123' } }
Match
The match
function returns a function for matching strings against a path:
- path String or array of strings.
- options (optional) (Extends pathToRegexp options)
- decode Function for decoding strings to params, or
false
to disable all processing. (default:decodeURIComponent
)
- decode Function for decoding strings to params, or
const fn = match("/foo/:bar");
Please note: path-to-regexp
is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
PathToRegexp
The pathToRegexp
function returns a regular expression for matching strings against paths. It
- path String or array of strings.
- options (optional) (See parse for more options)
- sensitive Regexp will be case sensitive. (default:
false
) - end Validate the match reaches the end of the string. (default:
true
) - delimiter The default delimiter for segments, e.g.
[^/]
for:named
parameters. (default:'/'
) - trailing Allows optional trailing delimiter to match. (default:
true
)
- sensitive Regexp will be case sensitive. (default:
const { regexp, keys } = pathToRegexp("/foo/:bar");
Compile ("Reverse" Path-To-RegExp)
The compile
function will return a function for transforming parameters into a valid path:
- path A string.
- options (See parse for more options)
- delimiter The default delimiter for segments, e.g.
[^/]
for:named
parameters. (default:'/'
) - encode Function for encoding input strings for output into the path, or
false
to disable entirely. (default:encodeURIComponent
)
- delimiter The default delimiter for segments, e.g.
const toPath = compile("/user/:id");
toPath({ id: "name" }); //=> "/user/name"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"
const toPathRepeated = compile("/*segment");
toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
const toPathRaw = compile("/user/:id", { encode: false });
toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
Stringify
Transform TokenData
(a sequence of tokens) back into a Path-to-RegExp string.
- data A
TokenData
instance
const data = new TokenData([
{ type: "text", value: "/" },
{ type: "param", name: "foo" },
]);
const path = stringify(data); //=> "/:foo"
Developers
- If you are rewriting paths with match and compile, consider using
encode: false
anddecode: false
to keep raw paths passed around. - To ensure matches work on paths containing characters usually encoded, such as emoji, consider using encodeurl for
encodePath
.
Parse
The parse
function accepts a string and returns TokenData
, the set of tokens and other metadata parsed from the input string. TokenData
is can used with match
and compile
.
- path A string.
- options (optional)
- encodePath A function for encoding input strings. (default:
x => x
, recommended:encodeurl
)
- encodePath A function for encoding input strings. (default:
Tokens
TokenData
is a sequence of tokens, currently of types text
, parameter
, wildcard
, or group
.
Custom path
In some applications, you may not be able to use the path-to-regexp
syntax, but still want to use this library for match
and compile
. For example:
import { TokenData, match } from "path-to-regexp";
const tokens = [
{ type: "text", value: "/" },
{ type: "parameter", name: "foo" },
];
const path = new TokenData(tokens);
const fn = match(path);
fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } }
Errors
An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.
Unexpected ?
or +
In past releases, ?
, *
, and +
were used to denote optional or repeating parameters. As an alternative, try these:
- For optional (
?
), use an empty segment in a group such as/:file{.:ext}
. - For repeating (
+
), only wildcard matching is supported, such as/*path
. - For optional repeating (
*
), use a group and a wildcard parameter such as/files{/*path}
.
Unexpected (
, )
, [
, ]
, etc.
Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To use these characters literally, escape them with a backslash, e.g. "\\("
.
Missing parameter name
Parameter names, the part after :
or *
, must be a valid JavaScript identifier. For example, it cannot start with a number or contain a dash. If you want a parameter name that uses these characters you can wrap the name in quotes, e.g. :"my-name"
.
Unterminated quote
Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character.
Express <= 4.x
Path-To-RegExp breaks compatibility with Express <= 4.x
in the following ways:
- Regexp characters can no longer be provided.
- The optional character
?
is no longer supported, use braces instead:/:file{.:ext}
. - Some characters have new meaning or have been reserved (
{}?*+@!;
). - The parameter name now supports all JavaScript identifier characters, previously it was only
[a-z0-9]
.
License
MIT
Top Related Projects
a glob matcher in javascript
glob functionality for node.js
Highly optimized wildcard and glob matching library. Faster, drop-in replacement to minimatch and multimatch. Used by square, webpack, babel core, yarn, jest, ract-native, taro, bulma, browser-sync, stylelint, nyc, ava, and many others! Follow micromatch's author: https://github.com/jonschlinkert
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot