Javascript: Convert Relative URLs to Absolute URLs

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:
- Javascript: Using Async/Await with Loops
- CSS & Javascript: Change Background Color on Scroll
- Javascript: Count the occurrences of each word in a string
- Vanilla Javascript: Detect a click outside an HTML element
- Calculate Variance and Standard Deviation in Javascript
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
0 Comments