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 use a regex.

For instance, we write

const r = new RegExp("^(?:[a-z]+:)?//", "i");
const isUrl = r.test("http://example.com");

to create a regex with the RegExp constructor.

We use ^(?:[a-z]+:)?// to check for the protocol part of the URL in our string.

And use i to check the string in a case insensitive manner.

Then we call r.test to check "http://example.com" is an absolute URL.

Conclusion

To test if a URL string is absolute or relative with JavaScript, we 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 *