Resolving relative URLs in JavaScript

后端 未结 3 502
傲寒
傲寒 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: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.).

提交回复
热议问题