als-path-to-regexp
v2.2.1
Published
A custom utility for converting URL path patterns to regular expressions, supporting dynamic segments, wildcards, and special character escaping.
Downloads
18
Maintainers
Readme
als-path-to-regexp
als-path-to-regexp
is a utility that allows developers to convert URL paths into regular expressions for flexible and comprehensive URL matching. This utility handles path segments with variables ({variable}
), wildcards (*
), fixed strings, and paths that contain combinations of special characters like ?
and *
.
als-path-to-regexp
is a powerful utility designed to handle various path patterns and combinations for flexible URL matching. With comprehensive test coverage, it ensures accuracy and reliability in your web application routing.
Installation
To install als-path-to-regexp
, use npm:
npm install als-path-to-regexp
Usage
const pathToRegexp = require('als-path-to-regexp');
// Match a simple static path
const staticRoute = pathToRegexp('/test/path');
console.assert(staticRoute('/test/path') !== null, 'Static path should match');
// Match a path with a variable
const userRoute = pathToRegexp('/user/{id}');
const userMatch = userRoute('/user/123');
console.assert(userMatch !== null && userMatch.id === '123', 'Parameterized path should match and extract params correctly');
// Match a path with a wildcard (*)
const wildcardRoute = pathToRegexp('/search/*/test');
console.assert(wildcardRoute('/search/query/test') !== null, 'Wildcard path should match');
// Match a path with question marks (?)
const questionRoute = pathToRegexp('/docs/item_?1');
const questionMatch = questionRoute('/docs/item_a1');
console.assert(questionMatch !== null, 'Path with "?" should match any single character');
Path Syntax
Variables (
{variable}
): Extract parameters from a path by enclosing them in curly braces, e.g.,/user/{id}
.Wildcard (
*
): Match any segment of a path. For example,/images/*/thumbnail
matches any path segment between/images/
and/thumbnail
.Question Mark (
?
): Represents any single character. For instance,/docs/item_?1
matches/docs/item_a1
or/docs/item_b1
.Combination of Characters: Mix variables, wildcards, and question marks to create flexible patterns.
Double Wildcard (
**
): Matches any sequence of segments until the end of the URL, effectively capturing everything following the pattern. This is particularly useful for flexible route handling within a specific path prefix or when you are unsure about the depth of the URL structure. For example,/files/**
will match/files/2023/jan/report.pdf
,/files/2023/feb/images/photo.jpg
, and so on, capturing the entire path after/files/
.
Examples
// Match all paths under a specific folder
const allFilesRoute = pathToRegexp('/files/**');
const filesMatch = allFilesRoute('/files/2023/jan/report.pdf');
console.assert(filesMatch !== null, 'Double wildcard should match any following segments');
// Using ** to capture all following segments and demonstrate its use in logging or advanced routing scenarios
const captureRoute = pathToRegexp('/api/data/**');
const captureMatch = captureRoute('/api/data/2023/stats');
console.assert(captureMatch !== null && captureMatch.rest === '2023/stats', 'Double wildcard should capture all following segments and include them in the "rest" property');
// Match a more complex path with multiple parameters and a wildcard
const complexRoute = pathToRegexp('/user/{id}/profile/{section}/*');
const complexMatch = complexRoute('/user/123/profile/settings/images');
console.assert(complexMatch !== null && complexMatch.id === '123' && complexMatch.section === 'settings', 'Complex path with parameters and wildcard should match and extract params correctly');
// Match a path with multiple wildcards
const multiWildcardRoute = pathToRegexp('/files/*/*');
console.assert(multiWildcardRoute('/files/images/avatar.jpg') !== null, 'Path with multiple wildcards should match');
// Handle extra slashes gracefully
const extraSlashRoute = pathToRegexp('/user///profile/{section}');
const extraSlashMatch = extraSlashRoute('/user/profile/settings');
console.assert(extraSlashMatch !== null && extraSlashMatch.section === 'settings', 'Path should ignore extra slashes and match correctly');
// Case-sensitive path matching
const caseSensitiveRoute = pathToRegexp('/User/{id}');
const caseSensitiveMatch = caseSensitiveRoute('/User/123');
console.assert(caseSensitiveMatch !== null && caseSensitiveMatch.id === '123', 'Path should match case-sensitive route');
console.assert(caseSensitiveRoute('/user/123') === null, 'Case-sensitive path should not match lowercase');
Extra properties for match function
When you run pathToRegexp
it returns not only match function, but also 3 properties:
segments
- the array of segments for this route- Each segment will include object
{ key, asterisk, rest, segment, regex }
where:key
- is the key for params or undefinedasterisk
- true if part is asterisk (*)rest
- true if part is rest (**)segment
- the segment valueregex
- the regex for part if it includes params or ?
- Each segment will include object
noRest
- if true, segments does not have restisDynamic
- if true, segments does have asterisk|rest|regex|key (which means it is dynamic route)path
- fixed path
const match = pathToRegexp('/user///profile/{section}')
match('/user/profile/123') // {section:123}
match.segments
match.noRest
match.isDynamic
match.path
Error Handling
If your path contains an invalid pattern, als-path-to-regexp
will throw an error, providing details about what went wrong. For instance, using ?
in static parts of the path will result in an error.
try {
pathToRegexp('/user/{id}/:');
} catch (e) {
console.error('Invalid path pattern:', e.message);
}
Notes and Recommendations
- Normalization: Paths are normalized using the
als-normalize-urlpath
package to ensure consistent behavior. - Special Characters: The utility supports special characters like
.
,+
,^
,$
,()
,|
,[
,]
,{
, and}
by escaping them properly in regular expressions. - Multiple Wildcards: While you can use multiple wildcards, ensure that the pattern doesn't conflict with other path segments.