Categories
JavaScript Answers

How to convert relative path to absolute using JavaScript?

Spread the love

Sometimes, we want to convert relative path to absolute using JavaScript.

In this article, we’ll look at how to convert relative path to absolute using JavaScript.

How to convert relative path to absolute using JavaScript?

To convert relative path to absolute using JavaScript, we can use the URL constructor.

For instance, we write

const url = new URL("../mypath", "http://www.example.com/search").href;

to create a new URL object with the relative path and the base path.

Then we get the absolute path with href.

As a result, url is 'http://www.example.com/mypath'.

Conclusion

To convert relative path to absolute using 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 *