Resolving relative URLs in JavaScript

后端 未结 3 483
傲寒
傲寒 2021-01-03 11:48

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

相关标签:
3条回答
  • 2021-01-03 12:06

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

    0 讨论(0)
  • 2021-01-03 12:06

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

    0 讨论(0)
  • 2021-01-03 12:09

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

    0 讨论(0)
提交回复
热议问题