path-to-regexp vs query-string vs uri-template vs url-template
URL 处理库
path-to-regexpquery-stringuri-templateurl-template类似的npm包:

URL 处理库

这些库用于处理和解析 URL 相关的字符串,提供了不同的功能和使用场景,帮助开发者在 Web 开发中更高效地管理路由和查询参数。它们各自有不同的特性和适用场景,适合不同的需求。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
path-to-regexp08,57556.3 kB87 个月前MIT
query-string06,90557.7 kB26 个月前MIT
uri-template044-14 年前MIT
url-template01947.99 kB12 年前BSD-3-Clause

功能对比: path-to-regexp vs query-string vs uri-template vs url-template

路径匹配

  • path-to-regexp:

    path-to-regexp 提供了将路径字符串转换为正则表达式的功能,允许开发者定义动态路由,并从 URL 中提取参数。它支持可选参数和通配符,适合复杂的路由匹配场景。

  • query-string:

    query-string 不涉及路径匹配,但可以与路径匹配结合使用,处理查询字符串中的参数。它的主要功能是解析和构建查询字符串,而不是路径。

  • uri-template:

    uri-template 支持使用 URI 模板进行路径匹配,允许开发者定义模板并从中提取参数,适合需要灵活路由的应用。

  • url-template:

    url-template 也支持路径匹配,提供更复杂的模板语法,适合需要动态生成 URL 的场景。

查询参数处理

  • path-to-regexp:

    path-to-regexp 不直接处理查询参数,但可以与其他库结合使用来实现完整的 URL 处理。

  • query-string:

    query-string 专注于查询参数的解析和字符串化,支持嵌套对象和数组的处理,提供简单的 API 来处理复杂的查询字符串。

  • uri-template:

    uri-template 主要处理 URI 模板,不专注于查询参数,但可以与其他库结合使用来实现完整的功能。

  • url-template:

    url-template 也不专注于查询参数处理,主要用于 URL 模板的生成和解析。

使用场景

  • path-to-regexp:

    适用于需要动态路由匹配的单页应用,特别是在 React Router 和 Vue Router 等框架中广泛使用。

  • query-string:

    适用于需要处理 GET 请求的场景,尤其是在发送和接收查询参数时,常用于 AJAX 请求和表单提交。

  • uri-template:

    适用于 RESTful API 的 URL 生成和解析,特别是在需要根据模板生成动态 URL 的场景。

  • url-template:

    适用于需要复杂 URL 生成和解析的应用,特别是在需要根据动态数据生成 URL 的场景。

学习曲线

  • path-to-regexp:

    相对简单,易于上手,适合大多数开发者,尤其是熟悉正则表达式的开发者。

  • query-string:

    非常易于使用,API 简单明了,适合初学者和需要快速实现查询参数处理的开发者。

  • uri-template:

    学习曲线适中,理解 URI 模板的语法和用法后,能够灵活使用。

  • url-template:

    相对复杂,需要理解模板语法,适合有一定经验的开发者。

扩展性

  • path-to-regexp:

    可以与其他库结合使用,灵活扩展,适合构建复杂的路由系统。

  • query-string:

    提供简单的 API,可以与其他库结合使用,扩展性强,适合处理复杂的查询参数。

  • uri-template:

    支持自定义模板,具有良好的扩展性,适合需要灵活处理 URI 的应用。

  • url-template:

    支持复杂的模板语法,扩展性强,适合需要动态生成 URL 的场景。

如何选择: path-to-regexp vs query-string vs uri-template vs url-template

  • path-to-regexp:

    选择 path-to-regexp 如果你需要将 URL 路径字符串转换为正则表达式,适用于路由匹配和动态路径解析,特别是在构建单页应用时。

  • query-string:

    选择 query-string 如果你需要解析和字符串化 URL 查询参数,特别是在处理 GET 请求时,它提供了简单易用的 API 来处理复杂的查询字符串。

  • uri-template:

    选择 uri-template 如果你需要支持 URI 模板的解析和生成,适合需要根据模板生成动态 URL 的场景,特别是在 RESTful API 中。

  • url-template:

    选择 url-template 如果你需要处理 URL 模板,支持更复杂的 URL 生成和解析,适用于需要动态构建 URL 的应用场景。

path-to-regexp的README

Path-to-RegExp

Turn a path string such as /user/:name into a regular expression.

NPM version NPM downloads Build status Build coverage License

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, TokenData object, or array of strings and TokenData objects.
  • options (optional) (Extends pathToRegexp options)
    • decode Function for decoding strings to params, or false to disable all processing. (default: decodeURIComponent)
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 the regexp for matching strings against paths, and an array of keys for understanding the RegExp#exec matches.

  • path String, TokenData object, or array of strings and TokenData objects.
  • 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)
const { regexp, keys } = pathToRegexp("/foo/:bar");

regexp.exec("/foo/123"); //=> ["/foo/123", "123"]

Compile ("Reverse" Path-To-RegExp)

The compile function will return a function for transforming parameters into a valid path:

  • path A string or TokenData object.
  • 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)
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 a TokenData object to a Path-to-RegExp string.

  • data A TokenData object.
const data = {
  tokens: [
    { 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 and decode: 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, which can be used with match and compile.

  • path A string.
  • options (optional)
    • encodePath A function for encoding input strings. (default: x => x, recommended: encodeurl)

Tokens

TokenData has two properties:

  • tokens A sequence of tokens, currently of types text, parameter, wildcard, or group.
  • originalPath The original path used with parse, shown in error messages to assist debugging.

Custom path

In some applications you may not be able to use the path-to-regexp syntax, but you still want to use this library for match and compile. For example:

import { match } from "path-to-regexp";

const tokens = [
  { type: "text", value: "/" },
  { type: "parameter", name: "foo" },
];
const originalPath = "/[foo]"; // To help debug error messages.
const path = { tokens, originalPath };
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.

Missing parameter name

Parameter names must be provided after : or *, for example /*path. They can be valid JavaScript identifiers (e.g. :myName) or JSON strings (:"my-name").

Unexpected ? or +

In past releases, ?, *, and + were used to denote optional or repeating parameters. As an alternative, try these:

  • For optional (?), use braces: /file{.:ext}.
  • For one or more (+), use a wildcard: /*path.
  • For zero or more (*), use both: /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 match these characters literally, escape them with a backslash, e.g. "\\(".

Unterminated quote

Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character. For example, :"foo.

Express <= 4.x

Path-To-RegExp breaks compatibility with Express <= 4.x in the following ways:

  • The wildcard * must have a name and matches the behavior of parameters :.
  • The optional character ? is no longer supported, use braces instead: /:file{.:ext}.
  • Regexp characters are not supported.
  • Some characters have been reserved to avoid confusion during upgrade (()[]?+!).
  • Parameter names now support valid JavaScript identifiers, or quoted like :"this".

License

MIT