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