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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.