Posted about 4 years ago. Visible to the public. Repeats. Linked content.

The Easiest Way to Parse URLs with JavaScript

A very clever hack to parse a structured URL object is to create a <a> element and set its href to the URL you want to parse.

You can then query the <a> element for its components like schema, hostname, port, pathname, query, hash:

Copy
var parser = document.createElement('a'); parser.href = 'http://heise.de/bar'; parser.hostname; // => 'heise.de' pathname = parser.pathname; // => '/bar' if (pathname[0] != '/') pathname = '/' + pathname // Fix IE11

One advantage vs. calling new URL(...) is that it works with incomplete URLs. So if all you have is /path it will fill in the hostname, protocol, etc. with data from the current page (as any <a> tag would do):

Copy
var parser = document.createElement('a'); parser.href = 'foo'; // set the URL you want to parse (resolving relative paths in the context of the current URL) parser.hostname; // => "makandracards.com" parser.pathname; // => "/makandra/29377-the-easiest-way-to-parse-urls-with-javascript/foo" if (pathname[0] != '/') pathname = '/' + pathname // Fix IE11

Caveat: IE11 will return the pathname without leading slash. Make to employ the fix as noted above.


Related topic: Javascript: Read params from url.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
1 day ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more