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
It turns out that the .href attribute of a A element (not .getAttribute('href'), but .href) returns the resolved (absolute) URL.
Nice pure JS solution that works without DOM: https://gist.github.com/1088850 (works everywhere but especially useful for server side JS).
In modern browsers and node, 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
In addition to .href, the URL object also gives you access to all of the URL components (protocol, host, path, search, hash, etc.).