如何在两个绝对URL之间获取相对URL?
获取两个绝对URL之间的相对路径
给定两个绝对URL:
const from = new URL("https://example.com") const to = new URL("https://example.com/about")
可以通过以下简单可靠的方法获取二者之间的相对URL,该方法支持所有要求的场景:
核心实现函数
function getRelativeURL(from, to) { // 跨源直接返回完整URL if (from.origin !== to.origin) { return to.href; } // 拆分路径为非空片段数组 const fromPathSegments = from.pathname.split('/').filter(Boolean); const toPathSegments = to.pathname.split('/').filter(Boolean); // 计算路径的最长公共前缀长度 let commonSegmentCount = 0; while (commonSegmentCount < fromPathSegments.length && commonSegmentCount < toPathSegments.length && fromPathSegments[commonSegmentCount] === toPathSegments[commonSegmentCount]) { commonSegmentCount++; } // 生成上跳层级 + 剩余目标路径 const upwardSteps = fromPathSegments.length - commonSegmentCount; const relativePathSegments = Array(upwardSteps).fill('..').concat(toPathSegments.slice(commonSegmentCount)); const relativePath = relativePathSegments.length > 0 ? relativePathSegments.join('/') : '.'; // 拼接查询参数与片段 return relativePath + to.search + to.hash; }
场景验证
根路径到子页面
const from = new URL("https://example.com"); const to = new URL("https://example.com/about"); console.log(getRelativeURL(from, to)); // 输出: about非子页面跳转
const from = new URL("https://example.com/some-page"); const to = new URL("https://example.com/some-other-page"); console.log(getRelativeURL(from, to)); // 输出: ../some-other-page带查询参数与片段
const from = new URL("https://example.com/a/b"); const to = new URL("https://example.com/a/c?foo=bar#section1"); console.log(getRelativeURL(from, to)); // 输出: ../c?foo=bar#section1不同源场景
const from = new URL("https://example.com"); const to = new URL("https://other-site.com/page"); console.log(getRelativeURL(from, to)); // 输出: https://other-site.com/page
说明
该方法生成的相对路径是可直接作为Anchor标签href属性的最短有效路径:
- 跨源时返回完整绝对URL,确保导航有效
- 同源时通过计算路径公共前缀,最小化上跳层级,同时完整保留目标URL的查询参数与锚点信息
内容的提问来源于stack exchange,提问作者Loris Sigrist
相关产品推荐
相关产品推荐

