MDN Web API 教程:深入理解 URL Pattern API
2025-07-07 02:17:28作者:侯霆垣
概述
URL Pattern API 是现代 Web 开发中一个强大的工具,它提供了一种声明式的方式来定义和匹配 URL 模式。这个 API 通过 URLPattern 接口实现,允许开发者创建复杂的 URL 匹配规则,这在构建路由系统、API 网关或任何需要 URL 处理的场景中特别有用。
核心概念
URL Pattern API 的核心是 URL 模式匹配语法,它借鉴了流行的 path-to-regexp 库的设计。这种语法支持多种匹配方式:
- 精确匹配:直接匹配固定的文本字符串
- 通配符:使用
*
匹配任意字符 - 命名捕获组:如
/books/:id
可以提取 URL 中的特定部分 - 非捕获组:使用
{}
定义可选或可重复的部分 - 正则表达式组:在
()
内使用正则表达式进行复杂匹配
URLPattern 接口
URLPattern 是 URL Pattern API 的核心接口,它表示一个可以匹配完整 URL 或其组成部分的模式。主要功能包括:
- 通过构造函数创建模式
- 使用 test() 方法测试 URL 是否匹配
- 使用 exec() 方法提取匹配结果和捕获组
模式语法详解
基础匹配
最简单的模式是直接匹配固定文本:
const pattern = new URLPattern({ pathname: "/about" });
console.log(pattern.test("https://example.com/about")); // true
命名捕获组
使用 :
前缀定义命名捕获组:
const pattern = new URLPattern({ pathname: "/users/:id" });
const result = pattern.exec("https://example.com/users/123");
console.log(result.pathname.groups.id); // "123"
正则表达式组
在捕获组中使用正则表达式进行更精确的匹配:
const pattern = new URLPattern("/posts/:id(\\d+)");
console.log(pattern.test("/posts/123")); // true
console.log(pattern.test("/posts/abc")); // false
修饰符
捕获组支持三种修饰符:
?
:可选+
:重复一次或多次*
:重复零次或多次
const optionalPattern = new URLPattern("/archive/:year?");
console.log(optionalPattern.test("/archive/2023")); // true
console.log(optionalPattern.test("/archive")); // true
通配符
*
通配符匹配任意字符:
const wildcardPattern = new URLPattern("/assets/*");
console.log(wildcardPattern.test("/assets/images/logo.png")); // true
高级特性
组定界符
使用 {}
定义组定界符,可以创建非捕获组:
const pattern = new URLPattern("/blog{/old}?");
console.log(pattern.test("/blog/old")); // true
console.log(pattern.test("/blog")); // true
自动前缀
在 pathname 中,组会自动添加 /
前缀:
const pattern = new URLPattern("/books/:id+");
console.log(pattern.test("/books/123/456")); // true
大小写敏感
默认情况下匹配是大小写敏感的,但可以通过选项调整:
const caseInsensitive = new URLPattern("/about", { ignoreCase: true });
console.log(caseInsensitive.test("/ABOUT")); // true
实际应用示例
路由系统
const routes = [
{ pattern: new URLPattern("/"), handler: homeHandler },
{ pattern: new URLPattern("/products/:id"), handler: productHandler },
{ pattern: new URLPattern("/blog/:year/:month?"), handler: blogHandler }
];
function route(url) {
for (const route of routes) {
const result = route.pattern.exec(url);
if (result) {
return route.handler(result.pathname.groups);
}
}
return notFoundHandler();
}
API 版本控制
const apiPattern = new URLPattern({
pathname: "/api/:version(v\\d+)/:endpoint"
});
const result = apiPattern.exec("/api/v2/users");
console.log(result.pathname.groups);
// { version: "v2", endpoint: "users" }
注意事项
- 正则表达式组有一些限制,如不能使用
^
和$
锚点 - 模式会自动规范化,如 Unicode 字符会被编码
- 组定界符不能嵌套
- 在 pathname 外的部分,组不会自动添加
/
前缀
总结
URL Pattern API 为 Web 开发者提供了一种强大而灵活的方式来处理 URL 匹配和解析。无论是构建复杂的路由系统,还是简单的 URL 验证,这个 API 都能提供简洁而强大的解决方案。通过掌握其丰富的模式语法,开发者可以轻松应对各种 URL 处理需求。