Validate URLs with the URL constructor

Also on X

A nice way to validate a URL without a regex: let new URL() try to parse it.

/**
 * Check if supplied href is a valid URL or not.
 * Note "example.com/contact" is not a valid URL.
 * The protocol has to be supplied as well:
 * => "https://example.com/contact"
 * => "mailto:iron.man@gmail.com"
 * => "tel:+188899956754"
 */
function isUrl(href: string) {
  try {
    new URL(href);
    return true;
  } catch (e) {
    return false;
  }
}

Via André Landgraf’s remix-isomorphic-link.

Update: browsers now ship this built in. URL.canParse(href) returns a boolean, no try/catch needed.

← All TILs