How to use the pathToRegexp function from path-to-regexp

Find comprehensive JavaScript path-to-regexp.pathToRegexp code examples handpicked from public code repositorys.

path-to-regexp.pathToRegexp is a function that generates a regular expression from a path string, which can be used to match and extract values from URLs.

233
234
235
236
237
238
239
240
241

if (typeof reducer === 'string' || path) {
    const usePath = path || reducer;
    resolverPath = this._normalizePath(usePath);
    resolverPath = resolverPath.replace(/\*/g, '(.*)');
    const pathMatch = pathToRegexp(resolverPath, [], { end: resolverPath === '' });

    reduce = (req, res, relativePostBack, pathContext, action) => {
        const actionMatches = action && (resolverPath === '/*' || pathMatch.exec(action));
fork icon4
star icon5
watch icon5

58
59
60
61
62
63
64
65
66
67
if (client == undefined) return;
let p, r, l;
switch (packet.topic) {
  case "to-parts":
    p = JSON.parse(packet.payload + '');
    r = pathToRegexp(p.targets, [], {});
    l = await items.utils.data();
    for (let i in l)
        r.exec(l[i].path) && this.notify("to-part", [l[i].id, {topic: p.topic, pid: p.pid, body: p.body}]);
    break;
fork icon0
star icon0
watch icon0

How does path-to-regexp.pathToRegexp work?

path-to-regexp.pathToRegexp is a function that takes a path string and returns a regular expression that can be used to match the path with optional parameters, which can be extracted as key-value pairs from the resulting match object. It supports named parameters, optional parameters, and wildcards.

0
1
2
3
4
5
6
7
8
9
10
// Express
const express = require('express');
// const cron = require("node-cron");


// const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
// pathToRegexp(path, keys?, options?)
// match(path)
// parse(path)
// compile(path)

fork icon0
star icon0
watch icon1

135
136
137
138
139
140
141
142
143
144
function parseAndAddRouteParameters(endpoints) {
    endpoints
        .filter(r => !r.path.includes('*'))
        .forEach(route => {
            const keys = []
            pathToRegexp(route.path, keys)
            route.addRouteParams(keys)
            keys.forEach(arg => route.path = route.path.replace(`:${arg.name}`, `{${arg.name}}`))
        })
}
fork icon0
star icon0
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const pathToRegexp = require("path-to-regexp");

const path = "/users/:id";

// Generate a regular expression pattern
const pattern = pathToRegexp.pathToRegexp(path, [], { sensitive: true });

// Test the pattern against a URL path
const urlPath = "/users/123";
const isMatch = pattern.test(urlPath);
console.log(isMatch); // Output: true

In this example, pathToRegexp.pathToRegexp() is used to generate a regular expression pattern based on the /users/:id path. The resulting pattern is then used to test if the URL path /users/123 matches the pattern.

122
123
124
125
126
127
128
129
130
131
let result = 'public'

const isMatch = regepx => {
  return regepx instanceof RegExp
    ? regepx.test(pathname)
    : pathToRegexp(regepx).exec(pathname)
}

for (const item of layouts) {
  let include = false
fork icon0
star icon0
watch icon1

37
38
39
40
41
42
43
44
45
46
47
48
        `${methods.toString()} \`${this.opts.name || path}\`: \`middleware\` must be a function, not \`${type}\``
      );
  }


  this.path = path;
  this.regexp = pathToRegexp(path, this.paramNames, this.opts);
};


/**
 * Returns whether request `path` matches route.
fork icon0
star icon0
watch icon1

+ 7 other calls in file