1

Should I expect any pitfalls if I would simple do this

function absoluteOrRelative(url)
{
  return url.indexOf(":") === -1 ? "relative" : "absolute";
}

The reason I ask is that I am uncertain if there is any way in which a colon character : might also occur in a relative URL?

Some URLs contain a so called "URI schemas", such as data:,ftp:,mailto:,blob:,file", and many more. While I feel uncertain if all of the possible schemas really imply the meaning of what constitues an URL, I would hope that the above code does "work", as any absolute URL to the most common http, https, file: schemas seems to be dealt with appropriately as well.

humanityANDpeace
  • 4,350
  • 3
  • 37
  • 63
  • Honestly, it depends on the meaning of "relative" and "absolute"; it appears as though your meaning says that if the URL has a scheme it is "absolute", but others would say that "//example.com/path" is an absolute URL... – Heretic Monkey Jul 15 '19 at 21:51
  • 1
    Using `//google.com` is a legitimate way to use an absolute URL, it just avoids specifying the protocol as the default usage is http. It is also possible to have a url contain `:` in the query string. In short, no, that is not reliable. – Travis J Jul 15 '19 at 21:52

1 Answers1

1

I think that a more reliable way to determine this is to use the built-in URL interface to construct a couple URL objects and compare origins.

return new URL(window.location).origin === new URL(url, window.location).origin;

This allows the browser to parse and figure all this out for you.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • thank! I will give it a try, this is really the kind of answer I was looking for, i.e. a way to robustly tell apart the realtive from an absolute ULR. However should I also consider the effect that the presence of a `` element might pose to your code? – humanityANDpeace Jul 15 '19 at 21:55
  • `return new URL(document.baseURI).origin === new URL(url,document.baseURI).origin` – humanityANDpeace Jul 17 '19 at 05:47