Read more

The Easiest Way to Parse URLs with JavaScript

Henning Koch
November 28, 2014Software engineer at makandra GmbH

Use the URL interface instead.

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

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

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.

If you use Unpoly Show archive.org snapshot you may also use up.util.parseUrl() Show archive.org snapshot , which implements the technique in this card with tests and all caveats fixed.


Related topic:

Posted by Henning Koch to makandra dev (2014-11-28 10:09)