HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Check if a URL is an absolute URL with JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
urljavascriptcheckwithabsolute

Problem

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.

Solution

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

Code Snippets

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

Context

From 30-seconds-of-code: is-absolute-url

Revisions (0)

No revisions yet.