path-to-regexp

repository·master·Indexed 27 days ago

https://github.com/pillarjs/path-to-regexp

An Express-style utility for converting path strings (e.g., /user/:id) into regular expressions for matching and parsing. Version 8.4.2 provides functions to match strings against paths, generate RegExps and keys via pathToRegexp(), transform parameters back into paths using compile(), and parse path strings into TokenData.

Tokens
1.9K
Snippets
4
Records
19
Agent score
44%

What's inside path-to-regexp

  1. Define path parameters and wildcards

    master

    Parameters

    Parameters match arbitrary strings in a path up to the end of the segment or the next token. Define them by prefixing a colon to the name (:foo).

    • Use valid JavaScript identifiers: :foo
    • Use double quotes for other characters: :"param-name"

    Wildcards

    Wildcard parameters match one or more characters across multiple segments. Prefix them with an asterisk (*foo).

  2. Troubleshoot common path-to-regexp errors

    master

    Missing parameter name

    Parameter names must follow : or *. Example: /*path is valid; /* is not.

    Unexpected ? or + symbols

    These are no longer supported for optional or repeating parameters. Use braces instead:

    • Optional (?): Use /file{.:ext} instead of /file.:ext?.
    • One or more (+): Use a wildcard /*path.
    • Zero or more (*): Use /files{/*path}.

    Unexpected RegExp characters

    Characters like (, ), [, and ] are no longer supported for RegExp features and are reserved. To match them literally, escape them with a backslash (e.g., "\\(")

    Express 4.x Compatibility

    If migrating from Express <= 4.x, note that:

    • Wildcards * must have a name.
    • The ? character is unsupported (use braces).
    • RegExp characters are not supported.
    • Certain characters are reserved: ()[]?+!.
  3. Use compile() to transform parameters into a path

    master

    The compile function (often called "Reverse" Path-To-RegExp) returns a function for transforming parameter objects into valid path strings.

    Parameters:

    • path: A String or TokenData object.
    • options:
      • delimiter: The default delimiter for segments. (default: '/')
      • encode: Function for encoding input strings for output into the path, or false to disable entirely. (default: encodeURIComponent)
    const { compile } = require("path-to-regexp");
    
    const toPath = compile("/user/:id");
    
    toPath({ id: "name" }); //=> "/user/name"
    toPath({ id: "café" }); //=> "/user/caf%C3%A9"
    
    // Using wildcards with compile
    const toPathRepeated = compile("/*segment");
    toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
    
    // Disabling encoding
    const toPathRaw = compile("/user/:id", { encode: false });
    toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
  4. Use match() to match strings against a path

    master

    The match function returns a function that takes a string and returns an object containing the matched path and its parameters.

    Parameters:

    • path: A String, TokenData object, or an array of strings and TokenData objects.
    • options (optional):
      • decode: Function for decoding strings to params, or false to disable all processing. (default: decodeURIComponent)
  5. Use pathToRegexp() to get a RegExp and keys

    master

    The pathToRegexp function returns a RegExp for matching strings against paths, and an array of keys to help understand the RegExp#exec matches.

    Parameters:

    • path: A String, TokenData object, or an array of strings and TokenData objects.
    • options (optional):
      • sensitive: If true, the Regexp will be case sensitive. (default: false)
      • end: If true, validates that the match reaches the end of the string. (default: true)
      • delimiter: The default delimiter for segments, e.g. [^/] for :named parameters. (default: '/')
      • trailing: Allows an optional trailing delimiter to match. (default: true)
    const { pathToRegexp } = require("path-to-regexp");
    
    const { regexp, keys } = pathToRegexp("/foo/:bar");
    
    regexp.exec("/foo/123"); //=> ["/foo/123", "123"]
  6. Use parse() to convert a path string to TokenData

    master

    The parse function accepts a string and returns a TokenData object, which can be used with match and compile functions.

    Parameters:

    • path: A String.
    • options (optional):
      • encodePath: A function for encoding input strings. (default: x => x, recommended: encodeurl)
  7. Use stringify() to convert TokenData to a path string

    master

    The stringify function transforms a TokenData object back into a Path-to-RegExp string.

    Parameters:

    • data: A TokenData object.
    const { stringify } = require("path-to-regexp");
    
    const data = {
      tokens: [
        { type: "text", value: "/" },
        { type: "param", name: "foo" },
      ],
    };
    
    const path = stringify(data); //=> "/:foo"
  8. Match a path string using match()

    master
    The match() function transforms a path pattern into a function that tests an input string. If the string matches the pattern, it returns a MatchResult containing the matched path and the extracted parameters. If it does not match, it returns false.