Categories
JavaScript Answers

How to Test if a URL String is Absolute or Relative with JavaScript?

Spread the love

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 .

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 *