Resolving relative URLs in JavaScript

Jeremy Dunck picture Jeremy Dunck · Oct 15, 2010 · Viewed 11.2k times · Source

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

Answer

Jeremy Dunck picture Jeremy Dunck · Dec 9, 2010

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