How to join relative URLs in JavaScript?

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.