Resolving relative URLs in JavaScript

11,029

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

The JavaScript URL constructor handles relative urls. So in your case:

    new URL("../g", "http://a/b/c/d;p?q").href

    // returns "http://a/b/g"
Share:
11,029
Jeremy Dunck
Author by

Jeremy Dunck

Updated on July 26, 2022

Comments

  • Jeremy Dunck
    Jeremy Dunck almost 2 years

    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/b/c/d;p?q and encounter an href value of "../g" (assume there's no <base> element). The resulting absolute would be: http://a/b/g.

    Is there a JS library that does this already? I'd have to believe so.

    For more info about what's needed, the spec: https://www.rfc-editor.org/rfc/rfc3986#section-5.4

  • Mark Amery
    Mark Amery almost 11 years
    In other words, the DOM property (accessed via someAnchorElement.href) returns the resolved URL, and the HTML attribute (accessed via someAnchorElement.getAttribute('href') or someAnchorElement.attributes.href) returns it as originally written in the HTML. (Well, even that isn't 100% true, but Googling 'prop vs attr' will throw up plenty of relevant discussion.)
  • tusharmath
    tusharmath almost 11 years
    Exactly you don't need a library to do this.
  • ericP
    ericP over 2 years
    Why would you prefer the .origin over window.location or document.location? That would break the OP's relative path ("../g"), as well as relative fragments or search strings.
  • Luca Fagioli
    Luca Fagioli over 2 years
    @ericP I do not remember why, frankly, but you are right, origin would not suit the OP's case. Anyway by having a second look at the OP's question, it seems that the base parameter should come from the attribute action of a form DOM element, not from the current location (although later in his question the "I'm on" may suggests otherwise). Regarding the search strings, according to his question he is not interested in keeping them. I have edited my answer with a more pertinent snippet.