Skip to content

109 Sandbox

A website made for testing

JavaScript function to parse a URL in a browser

Published ·UPD ·In JavaScript

A small function useful for browsers that do not support the URL interface. It was posted by Freddie Fujiwara at Stack Overflow.

function parseURL(href) {
  let location = document.createElement('a');

  location.href = href;

  return location;
}

The function uses the HTMLAnchorElement interface provided by the DOM and returns an object with the properties supported by HTMLAnchorElement: host, hostname, protocol etc.

Documentation and references