Categories
JavaScript Answers

How to test if a URL string is absolute or relative with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *