Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving relative URLs in JavaScript

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

like image 641
Jeremy Dunck Avatar asked Oct 15 '10 14:10

Jeremy Dunck


People also ask

How are relative URLs resolved?

Relative URLs may contain relative path components (".." means one level up in the hierarchy defined by the path), and may contain fragment identifiers. Relative URLs are resolved to full URLs using a base URL.

What is relative URL example?

Rather than including the entire URL for each page you link, relative URLs cut down on the workload and time needed. For example, coding /about/ is much faster than https://www.example.com/about .

What are the three types of relative URL?

type: It specifies the type of the server in which the file is located. address: It specifies the address or location of the internet server. path: It specifies the location of the file on the internet server.


1 Answers

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

like image 80
Jeremy Dunck Avatar answered Sep 22 '22 03:09

Jeremy Dunck