Back to 30 Seconds Of Code

Check if a URL is an absolute URL with JavaScript

content/snippets/js/s/is-absolute-url.md

14.0.0634 B
Original Source

An absolute URL is a URL that includes a scheme (e.g. https://, ftp://, mailto:). This is in contrast to a relative URL, which doesn't include a scheme and is typically used to reference resources within the same domain.

Given that definition, we can easily write a regular expression to check if a string is an absolute URL. We can then use RegExp.prototype.test() to check if the string matches the pattern.

js
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false