To test if a URL string is absolute or relative with JavaScript, we can use a regex to do the check.
For instance, we can write:
const r = new RegExp('^(?:[a-z]+:)?//', 'i');
console.log(r.test('http://example.com'));
console.log(r.test('HTTP://EXAMPLE.COM'));
console.log(r.test('ftp://example.com/file.txt'));
console.log(r.test('//cdn.example.com/lib.js'));
console.log(r.test('test'));
We create the regex with the ^(?:[a-z]+:)?//’
pattern to check if the URL starts something with ://
after it and more path segments appended after that.
The part before ://
is optional for a URL to be considered absolute.
Then we use the test
method to check if each URL is absolute or relative.
If it’s absolute, test
returns true
. Otherwise, it returns false
.
Therefore, the first 4 console logs logs true
and the last one logs false
.