解析 JavaScript 中的相对 URL
我正在构建一个 JS 库,它需要查看 form[action] 和 a[href] 值并将它们解析为绝对 URL。
例如,我在 http://a/b/c/d;p?q 上遇到 href 值“../g”(假设没有
有没有 JS 库可以做到这一点?我不得不相信是这样。
有关所需内容的更多信息,请参阅规范: https://www.rfc-editor.org/rfc/rfc3986#section- 5.4
I'm building a JS library which has a requirement of looking at form[action] and a[href] values and resolving them into absolute URLs.
For example, I'm on http://a/b/c/d;p?q and encounter an href value of "../g" (assume there's no <base> element). The resulting absolute would be: http://a/b/g.
Is there a JS library that does this already? I'd have to believe so.
For more info about what's needed, the spec:
https://www.rfc-editor.org/rfc/rfc3986#section-5.4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在现代浏览器和节点中,内置的 URL 构造函数会处理此问题:
(yields
http://a.example/with/a/long/path.file?newSearch
)如果您希望基如果相对于当前文档,您可以明确地执行此操作:
除了
.href
之外,URL
对象还允许您访问所有 URL 组件(协议、主机) 、路径、搜索、哈希等)。返回(从绝对 URL 到相对 URL)
In modern browsers and node, the built-in URL constructor handles this:
(yields
http://a.example/with/a/long/path.file?newSearch
)If you want the base to be relative to the current document, you can do that explicitly:
In addition to
.href
, theURL
object also gives you access to all of the URL components (protocol, host, path, search, hash, etc.).Going back (from absolute URLs to relative URLs) takes some code.
事实证明,A 元素的
.href
属性(不是.getAttribute('href')
,而是.href
)返回已解析的(绝对)URL。It turns out that the
.href
attribute of a A element (not.getAttribute('href')
, but.href
) returns the resolved (absolute) URL.很好的纯 JS 解决方案,无需 DOM 即可工作: https://gist.github.com/1088850 (适用于任何地方但对于服务器端 JS 特别有用)。
Nice pure JS solution that works without DOM: https://gist.github.com/1088850 (works everywhere but especially useful for server side JS).
JavaScript URL 构造函数处理相对 URL。所以在你的情况下:
The JavaScript URL constructor handles relative urls. So in your case: