path-to-regexp vs template-url vs query-string vs uri-js vs uri-template vs url-template
URL 处理和模板
path-to-regexptemplate-urlquery-stringuri-jsuri-templateurl-template类似的npm包:

URL 处理和模板

URL 处理和模板库提供了一组工具,用于解析、构建和操作 URL(统一资源定位符)。这些库支持处理 URL 的各个部分,包括路径、查询字符串和哈希值,允许开发者轻松地进行 URL 模板化、参数化和编码解码操作。它们在 Web 开发中非常有用,尤其是在构建动态应用程序、处理 API 请求或实现路由功能时。path-to-regexp 是一个用于将路径字符串转换为正则表达式的库,支持动态路由和参数提取。query-string 专注于解析和序列化查询字符串,提供简单易用的 API 来处理 URL 中的参数。template-url 允许开发者使用模板字符串创建动态 URL,支持插入变量和处理嵌套模板。uri-js 是一个全面的 URL 解析和构建库,遵循 RFC 3986 标准,支持处理复杂的 URL 结构。uri-template 实现了 URI 模板规范,支持从模板生成 URL 和从 URL 提取参数。url-template 是一个轻量级的库,提供 URI 模板功能,支持解析和生成基于模板的 URL,适合需要简单模板化功能的应用。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
path-to-regexp153,735,2598,58060 kB71 天前MIT
template-url70,1672-1411 年前ISC
query-string06,90357.7 kB26 个月前MIT
uri-js0318-305 年前BSD-2-Clause
uri-template044-04 年前MIT
url-template01947.99 kB12 年前BSD-3-Clause

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

路径处理

  • path-to-regexp:

    path-to-regexp 允许将路径字符串(如 /users/:id)转换为正则表达式,以便从 URL 中提取动态参数。它支持嵌套和可选参数,适合复杂路径的处理。

  • uri-js:

    uri-js 提供全面的 URL 解析和构建功能,支持处理 URL 的各个部分,包括路径、查询和哈希。它遵循 RFC 3986 标准,确保对各种 URL 形式的兼容性。

  • uri-template:

    uri-template 支持从 URI 模板生成路径和查询部分,允许根据模板动态构建 URL。它特别适合需要根据模板结构生成 URL 的应用。

  • url-template:

    url-template 提供简单的 URI 模板解析和生成,支持从模板创建路径和查询字符串。它适合需要轻量级模板功能的应用。

查询字符串处理

  • query-string:

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

  • uri-js:

    uri-js 提供基本的查询字符串解析和构建功能,但不是其主要关注点。它支持对查询部分的标准化处理,确保与其他 URL 组件的一致性。

  • uri-template:

    uri-template 支持从模板生成查询字符串,但需要手动定义模板。它适合需要根据特定结构生成查询参数的应用。

  • url-template:

    url-template 提供简单的查询字符串生成和解析,特别是在与 URI 模板结合使用时。它适合需要快速处理查询参数的轻量级应用。

模板功能

  • template-url:

    template-url 允许使用模板字符串动态生成 URL,支持插入变量和处理嵌套模板。它提供灵活的模板化功能,适合需要构建动态链接的应用。

  • uri-template:

    uri-template 实现了 URI 模板规范,支持从模板生成 URL 和从 URL 提取参数。它提供标准化的模板处理方法,适合需要遵循规范的应用。

  • url-template:

    url-template 提供简单的 URI 模板功能,支持解析和生成基于模板的 URL。它轻量级且易于使用,适合对性能和复杂性要求较低的应用。

标准遵循

  • uri-js:

    uri-js 严格遵循 URL 相关的 RFC 标准,确保对各种 URL 形式的正确解析和构建。它特别关注安全性和合规性,适合需要处理敏感数据的应用。

  • uri-template:

    uri-template 遵循 URI 模板规范,提供标准化的模板解析和生成方法。它适合需要在不同系统之间共享模板化 URL 的应用。

  • url-template:

    url-template 遵循 URI 模板的基本原则,提供简单易用的模板功能。它适合对标准遵循要求不那么严格的轻量级应用。

代码示例

  • path-to-regexp:

    path-to-regexp 示例:

    import { pathToRegexp, match } from 'path-to-regexp';
    
    // 定义路径和正则表达式
    const path = '/users/:id';
    const keys = [];
    const regex = pathToRegexp(path, keys);
    
    // 匹配 URL
    const url = '/users/123';
    const matchResult = regex.exec(url);
    
    // 提取参数
    const params = match(path)(url);
    console.log(params.params); // { id: '123' }
    
  • template-url:

    template-url 示例:

    import templateUrl from 'template-url';
    
    // 定义模板和数据
    const urlTemplate = 'https://api.example.com/users/{id}/posts/{postId}';
    const data = { id: 123, postId: 456 };
    
    // 生成 URL
    const url = templateUrl(urlTemplate, data);
    console.log(url); // https://api.example.com/users/123/posts/456
    
  • query-string:

    query-string 示例:

    import queryString from 'query-string';
    
    // 解析查询字符串
    const parsed = queryString.parse('?name=John&age=30');
    console.log(parsed); // { name: 'John', age: '30' }
    
    // 序列化对象为查询字符串
    const stringified = queryString.stringify({ name: 'Jane', age: 25 });
    console.log(stringified); // name=Jane&age=25
    
  • uri-js:

    uri-js 示例:

    import { URI } from 'uri-js';
    
    // 解析 URL
    const uri = URI.parse('https://example.com:8080/path?query=1#fragment');
    console.log(uri);
    
    // 构建 URL
    const newUri = URI.serialize(uri);
    console.log(newUri);
    
  • uri-template:

    uri-template 示例:

    import { UriTemplate } from 'uri-template';
    
    // 创建 URI 模板
    const template = new UriTemplate('https://api.example.com/users/{id}/posts/{postId}');
    
    // 生成 URL
    const url = template.expand({ id: 123, postId: 456 });
    console.log(url); // https://api.example.com/users/123/posts/456
    
    // 提取参数
    const params = template.extract('https://api.example.com/users/123/posts/456');
    console.log(params); // { id: '123', postId: '456' }
    
  • url-template:

    url-template 示例:

    import { parse, compile } from 'url-template';
    
    // 解析 URL 模板
    const template = parse('https://api.example.com/users/{id}/posts/{postId}');
    
    // 生成 URL
    const url = template.expand({ id: 123, postId: 456 });
    console.log(url); // https://api.example.com/users/123/posts/456
    
    // 提取参数
    const compiled = compile('https://api.example.com/users/{id}/posts/{postId}');
    const params = compiled.parameters({ id: 123, postId: 456 });
    console.log(params); // { id: 123, postId: 456 }
    

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

  • path-to-regexp:

    选择 path-to-regexp 如果您需要将路径字符串转换为正则表达式,以便从 URL 中提取动态参数。它特别适合路由库和需要解析路径模式的应用。

  • template-url:

    选择 template-url 如果您需要根据模板字符串动态生成 URL。它支持插入变量和处理嵌套模板,适合需要构建动态链接的应用。

  • query-string:

    选择 query-string 如果您主要处理 URL 的查询字符串部分。它提供了简单的 API 来解析、序列化和处理查询参数,适合需要频繁操作 URL 参数的应用。

  • uri-js:

    选择 uri-js 如果您需要一个全面的 URL 解析和构建解决方案,支持复杂的 URL 结构和严格的标准遵循。它适合需要处理各种 URL 形式的应用,尤其是在安全性和合规性方面要求较高的场景。

  • uri-template:

    选择 uri-template 如果您需要实现 URI 模板规范,以便从模板生成 URL 或从 URL 中提取参数。它适合需要处理模板化 URL 的应用,特别是在 API 设计和文档生成方面。

  • url-template:

    选择 url-template 如果您需要一个轻量级的库来处理 URI 模板。它提供简单的 API 来解析和生成基于模板的 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, param, 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: "param", name: "foo" },
];
const originalPath = "/[foo]"; // To help debug error messages.
const path = { tokens, originalPath };
const fn = match(path);

fn("/test"); //=> { path: '/test', 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