Resolving relative URLs in JavaScript

白昼怎懂夜的黑 提交于 2019-12-18 17:34:20

问题


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: http://tools.ietf.org/html/rfc3986#section-5.4


回答1:


It turns out that the .href attribute of a A element (not .getAttribute('href'), but .href) returns the resolved (absolute) URL.




回答2:


In modern browsers, the built-in URL constructor handles this:

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)

If you want the base to be relative to the current document, you can do that explicitly:

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

The URL object also gives you access to all of the URL components (protocol, host, path, search, hash, etc.).




回答3:


Nice pure JS solution that works without DOM: https://gist.github.com/1088850 (works everywhere but especially useful for server side JS).



来源:https://stackoverflow.com/questions/3943281/resolving-relative-urls-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!