npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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

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

  1. Variables ({variable}): Extract parameters from a path by enclosing them in curly braces, e.g., /user/{id}.

  2. Wildcard (*): Match any segment of a path. For example, /images/*/thumbnail matches any path segment between /images/ and /thumbnail.

  3. Question Mark (?): Represents any single character. For instance, /docs/item_?1 matches /docs/item_a1 or /docs/item_b1.

  4. Combination of Characters: Mix variables, wildcards, and question marks to create flexible patterns.

  5. 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 undefined
      • asterisk - true if part is asterisk (*)
      • rest - true if part is rest (**)
      • segment - the segment value
      • regex - the regex for part if it includes params or ?
  • noRest - if true, segments does not have rest
  • isDynamic - 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.