Creation:2026-06-22Last update:2026-06-22
将此文档参考到您的 AI 助手ChatGPTClaudeDeepSeekGoogle AI modeGeminiPerplexityMistralGrok
使用您最喜欢的AI助手总结文档,并引用此页面和AI提供商
版本历史
- "初始文档"v9.0.02026/6/22
此页面的内容已使用 AI 翻译。
查看英文原文的最新版本Edit this doc
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy
Copy doc Markdown to clipboard
文档: intlayer 中的 comparePaths 函数
描述
comparePaths 函数在忽略区域设置(locale)段、协议/主机名、查询字符串、哈希值和尾部斜杠的情况下,比较两个 URL 或路径是否相等。这是确定导航链接是否指向当前页面的推荐方法(例如,用于高亮显示活动链接),而无需编写自己(容易出错)的规范化逻辑。
它在内部重用了 getPathWithoutLocale 来去除区域设置段,因此它会遵循您配置的路由模式和区域设置。
该包还导出了底层的 normalizePath 辅助函数,它返回用于比较的、与区域设置无关的规范路径名。
主要特性:
- 与区域设置无关的比较(
/zh/about与/about匹配) - 适用于绝对 URL 和相对路径
- 忽略查询字符串、哈希值和尾随斜杠
- 容忍缺少前导斜杠和空值(规范化为
/) - 轻量级 — 构建在
getPathWithoutLocale之上
函数签名
typescript
复制代码
复制代码到剪贴板
comparePaths( pathname: string, // 必填 href: string, // 必填 locales?: Locales[] // 可选): booleannormalizePath( inputUrl: string, // 必填 locales?: Locales[] // 可选): string参数
pathname: string- 描述: 要比较的第一个 URL 字符串或路径名(通常是当前路径)。
- 类型:
string - 必填: 是
href: string- 描述: 要比较的第二个 URL 字符串或路径名(通常是导航链接的
href)。 - 类型:
string - 必填: 是
- 描述: 要比较的第二个 URL 字符串或路径名(通常是导航链接的
locales: Locales[]- 描述: 支持的区域设置的可选数组。默认为项目中配置的区域设置。
- 类型:
Locales[] - 必填: 否 (可选)
返回值
- 类型:
boolean - 描述: 当两个输入都解析为相同的与区域设置无关的路径时返回
true,否则返回false。
示例用法
基本用法
typescript
复制代码
复制代码到剪贴板
import { comparePaths } from "intlayer";
comparePaths("/ru/path", "/path"); // true
comparePaths("/ru/path/", "/path"); // true
comparePaths("/ru/path", "/path/"); // true
comparePaths("/ru/", "/"); // true
comparePaths("/ru", "/"); // true
comparePaths("ru/path", "/path"); // true
comparePaths("", "/"); // true
comparePaths("/ru", ""); // true
comparePaths("/ru/path", "/other"); // false绝对和相对 URL
typescript
复制代码
复制代码到剪贴板
import { comparePaths } from "intlayer";comparePaths("https://example.com/ru/path", "/path"); // true高亮活动导航链接
tsx
复制代码
复制代码到剪贴板
import { comparePaths } from "intlayer";import { useLocation } from "react-router";const NavLink = ({ href, children }) => { const { pathname } = useLocation(); const isActive = comparePaths(pathname, href); return ( <a href={href} aria-current={isActive ? "page" : undefined}> {children} </a> );};normalizePath
normalizePath 返回由 comparePaths 使用的、与区域设置无关的规范路径名。它去除了区域设置段、协议/主机、查询字符串和哈希,确保单个前导斜杠,删除任何尾随斜杠(根目录除外),对于空值则回退为 /。
typescript
复制代码
复制代码到剪贴板
import { normalizePath } from "intlayer";
normalizePath("/ru/path"); // "/path"
normalizePath("/ru/path/"); // "/path"
normalizePath("ru/path"); // "/path"
normalizePath("/ru/"); // "/"
normalizePath("/ru"); // "/"
normalizePath(""); // "/"
normalizePath("https://example.com/ru/path"); // "/path"相关函数
getPathWithoutLocale: 从 URL 或路径中删除区域设置段。getPrefix: 获取给定区域设置的 URL 前缀。getLocalizedUrl: 为特定区域设置生成本地化 URL。
TypeScript
typescript
复制代码
复制代码到剪贴板
function normalizePath(inputUrl: string, locales?: Locales[]): string;function comparePaths( pathname: string, href: string, locales?: Locales[]): boolean;