Categories
JavaScript Answers

How to join relative URLs in JavaScript?

Spread the love

Sometimes, we want to join relative URLs in JavaScript.

In this article, we’ll look at how to join relative URLs in JavaScript.

How to join relative URLs in JavaScript?

To join relative URLs in JavaScript, we can use the URL constructor.

For instance, we write:

const {
  href
} = new URL('../../address', 'http://www.example.com/more/evenmore/')
console.log(href)

We use the URL constructor to combine the relative URL with the base URL.

We then get the combined URL from the href property.

Therefore, href is 'http://www.example.com/address'.

Conclusion

To join relative URLs in JavaScript, we can use the URL constructor.

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 *