Resolving relative URLs in JavaScript

一个人想着一个人 提交于 2019-11-30 15:45:05
Jeremy Dunck

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

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.).

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

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