snippetjavascriptTip
Check if a URL is an absolute URL with JavaScript
Viewed 0 times
urljavascriptcheckwithabsolute
Problem
An absolute URL is a URL that includes a scheme (e.g.
Given that definition, we can easily write a regular expression to check if a string is an absolute URL. We can then use
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'); // falseCode 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'); // falseContext
From 30-seconds-of-code: is-absolute-url
Revisions (0)
No revisions yet.