Javascript: Convert Relative URLs to Absolute URLs

Last updated on September 1, 2022 Pennywise Loading... Post a comment

In Javascript, you can easily convert a relative URL to an absolute URL like so:

const absoluteURL = new URL(relativeURL, window.location.href).href;

This works well regardless your relative URL starts with a slash (“/”) or not. Below is a concrete example:

// Define a reusable function
function relativeToAbsolute(relativeURL) {
     return new URL(relativeURL, 'https://www.kindacode.com').href;
}

// a URL starts with a slash "/"
console.log(relativeToAbsolute('/some-directory/index.html'));

// a URL starts without a slash "/"
console.log(relativeToAbsolute('article/welcome-to-kindacode-com'));

Output:

https://www.kindacode.com/some-directory/index.html
https://www.kindacode.com/article/welcome-to-kindacode-com

Alternative

Another way to do the same thing:

// Define a reusable function
function relativeToAbsolute(relativeURL) {
     const a = document.createElement('a');
     a.href = relativeURL;
     return a.href;
 }

// a URL starts with a slash "/"
console.log(relativeToAbsolute('/some-directory/index.html'));

// a URL starts without a slash "/"
console.log(relativeToAbsolute('article/welcome-to-kindacode-com'));

That’s it. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like