Convert relative path to absolute using JavaScript
Quickly whip your relative URLs into absolute shape by tapping into the power of the new URL()
constructor. This method is ready to roll in modern browsers - just feed it the relative path and document.baseURI
as the base:
With this one-liner, you've turned your once shy and retiring relative URL into a confident and worldly absolute URL!
Diving into the URL API
The URL API is a highly efficient and recommended tool to barter between relative paths and absolute URLs in JavaScript. It's fast, it's easy, and best of all, it takes on board the responsibility of handling and resolving paths so you don't have to! Here's how:
- Sorcery with symbols: Whether it's a
.
implying the same directory, or a..
gesture indicating the parent directory, the URL API simplifies and resolves these path notations for us. - Query quirk handler: If your URL is flaunting query strings and anchors, no problem! The URL API is up for the challenge.
- Protocol peacemaker: It even handles protocol-relative URLs (those sneaky ones starting with
//
).
All you need to do is to provide a relative path and a base path:
And voila! You're done!
When the URL API is off-duty
Though the URL API is quite the superhero, there might be times (like in non-browser environments), when you need to manually intervene in relative-to-absolute path conversion. Fear not, here are some tricks up your sleeve:
Crafting an absolutePath
function
A homemade function using a bag of string manipulations would effectively resolve the path navigation symbols ".." and ".":
Dynamic document.baseURI
to the rescue
document.baseURI
, the chameleon it is, fetches the dynamic base path based on the current document's absolute base URL:
The safety net for bytecode blunders
Ensure your function doesn't trip over unexpected or invalid inputs:
Validation of paths can be your safety net against runtime errors.
Beyond the code
Non-HTTP(s) protocols
While browsers handle different protocols, non-browser environments might need you to get your hands a little dirty. But remember, while getting dirty, stay clean (of bugs!).
Trailing slashes-a-go-go
Watch out for a trailing slash in either the base URL or the relative path. Your manual conversion function should handle them like a pro:
Bye bye, external libraries
Avoid external libraries: they can be weighty and bring unwanted guests (aka dependencies). In short: let's stick to vanilla JavaScript for a streamlined solution.
Was this article helpful?