Sometimes, we want to test if a URL string is absolute or relative with JavaScript.
In this article, we’ll look at how to test if a URL string is absolute or relative with JavaScript.
How to test if a URL string is absolute or relative with JavaScript?
To test if a URL string is absolute or relative with JavaScript, we can use a regex.
For instance, we write:
const r = new RegExp('^(?:[a-z]+:)?//', 'i');
console.log(r.test('http://example.com'));
console.log(r.test('test'));
We create a regex with the RegExp constructor that checks if there’s a protocol before the rest of the URL.
^(?:[a-z]+:)?/ checks for the protocol.
Then we call test on it with some URL strings to test.
Therefore, the console log should return true and false respectively since only absolute URLs have the protocol in front of it.
Conclusion
To test if a URL string is absolute or relative with JavaScript, we can use a regex.