url pattern api 是专为 url 多维语义匹配设计的原生方案,非正则替代品; pathname 模式需显式定义,支持 :param、*、?、+ 等语法,test() 返回布尔值,exec() 返回含分组的完整匹配对象,需搭配 new url 和 urlsearchparams 使用,并须兼容性兜底。

URL Pattern API 能直接匹配并结构化解析路径,但仅在 Chromium 110+ 和 Safari 16.4+ 中可用,Firefox 尚未实现;它不是正则替代品,而是专为 URL 多维语义匹配设计的原生方案。
URLPattern 构造时 pathname 模式语法怎么写
路径匹配必须写在 pathname 属性里,其他部分(如 protocol、hostname)可选但独立生效。动态参数用 :param,通配符用 *,可选段用 ?,重复段用 +:
-
new URLPattern({ pathname: "/users/:id" })→ 匹配/users/123,exec().pathname.groups.id得到"123" -
new URLPattern({ pathname: "/posts/:year/:month?/:slug+" })→ 匹配/posts/2024/05/hello-world或/posts/2024,groups.slug是数组 -
new URLPattern({ pathname: "/api/*" })→ 匹配/api/v1/users,exec().pathname.groups[0]是"v1/users"
注意::param 只捕获单一段(不含 /),* 才捕获含斜杠的子路径;不支持嵌套括号或自定义正则字符类。
test() 和 exec() 的实际区别在哪
test() 只返回布尔值,适合快速守卫路由;exec() 返回完整匹配对象,含各维度分组和原始输入信息:
文章转信息图。将文章/笔记转化为手机可读的 HTML 信息图,自动匹配视觉风格。触发场景:文章转图、笔记转图、信息图、转小红书图、做张图、可视化这篇文章、文生图。
-
pattern.test("https://example.com/users/42")→true,但拿不到42 -
const result = pattern.exec("https://example.com/users/42")→result.pathname.groups.id === "42",且result.hostname是"example.com" - 如果构造时没设
hostname,exec()仍会解析并填充该字段,但不参与匹配逻辑
别在循环里反复调用 exec() 做性能敏感匹配——提前缓存 URLPattern 实例,它本身不可变且轻量。
为什么不能用 URLPattern 替代 new URL() 解析任意 URL
URLPattern 不是解析器,而是**模式匹配器**;它不处理编码解码、相对路径补全或协议标准化:
-
new URL("/foo%20bar", "https://a.com")→ 正确解码并拼出完整 URL;URLPattern对%20视为字面字符,不自动 decode -
new URL("api/users", "https://a.com/")→ 自动补全为https://a.com/api/users;URLPattern的pathname模式只比对字符串,不理解相对路径语义 - 想提取查询参数?得搭配
URLSearchParams单独处理url.search,URLPattern的search属性只支持简单键值匹配(如search: "id=:id"),不支持复杂逻辑
真正需要的是组合:先用 new URL(input) 标准化输入,再用 URLPattern.exec() 提取结构化路径段——两者职责分明,缺一不可。
最容易被忽略的是兼容性兜底:生产环境必须检测 typeof URLPattern !== "undefined",否则在 Firefox 或旧 Chrome 里直接报 ReferenceError;不要假设它已普及,尤其当目标用户包含企业内网环境时。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










