解析JavaScript中的相对URL

时间:2010-10-15 14:41:25

标签: javascript html url rfc3986

我正在构建一个JS库,它需要查看form [action]和[href]值并将它们解析为绝对URL。

例如,我在http://a/b/c/d;p?q并且遇到href值“../g”(假设没有< base>元素)。结果绝对值为:http://a/b/g

是否有JS库已经这样做了?我不得不相信。

有关所需内容的更多信息,请参阅: http://tools.ietf.org/html/rfc3986#section-5.4

4 个答案:

答案 0 :(得分:10)

事实证明,A元素的.href属性(不是.getAttribute('href'),但是.href)会返回已解析的(绝对)网址。

答案 1 :(得分:2)

在现代浏览器中,内置的URL构造函数处理:

u = (new URL("?newSearch",
             "http://a.example/with/a/long/path.file?search#fragment")).href

(收益率http://a.example/with/a/long/path.file?newSearch

如果您希望base相对于当前文档,您可以明确地执行此操作:

u = (new URL("?newSearch", document.location)).href

URL对象还允许您访问所有URL组件(协议,主机,路径,搜索,哈希等)。

答案 2 :(得分:1)

没有DOM的好的纯JS解决方案: https://gist.github.com/1088850(适用于所有地方,但对服务器端JS特别有用)。

答案 3 :(得分:1)

为了考虑所有当前的 URL 变量(protocolport 号),您应该使用 window.location.origin 作为 base 参数:

new URL("/my-relative-url", window.location.origin);