简体   繁体   English

解析 JavaScript 中的相对 URL

[英]Resolving relative URLs in JavaScript

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.我正在构建一个 JS 库,它需要查看 form[action] 和 a[href] 值并将它们解析为绝对 URL。

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).例如,我在http://a/b/c/d;p?q 上遇到一个 href 值“../g”(假设没有 <base> 元素)。 The resulting absolute would be: http://a/b/g .结果绝对值将是: http://a/b/g

Is there a JS library that does this already?是否有一个 JS 库可以做到这一点? I'd have to believe so.我不得不相信。

For more info about what's needed, the spec: http://tools.ietf.org/html/rfc3986#section-5.4有关所需内容的更多信息,请参阅规范: http : //tools.ietf.org/html/rfc3986#section-5.4

事实证明, A 元素的.href属性(不是.getAttribute('href') ,而是.href )返回解析的(绝对)URL。

In modern browsers and node, the built-in URL constructor handles this:在现代浏览器和节点中,内置的 URL 构造函数处理这个:

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

(yields http://a.example/with/a/long/path.file?newSearch ) (产生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:如果您希望基础相对于当前文档,您可以明确地这样做:

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

In addition to .href , the URL object also gives you access to all of the URL components (protocol, host, path, search, hash, etc.).除了.hrefURL对象还允许您访问所有 URL 组件(协议、主机、路径、搜索、哈希等)。

不错的纯 JS 解决方案,无需 DOM: https : //gist.github.com/1088850 (适用于任何地方,但对服务器端 JS 尤其有用)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM