Explain Codes LogoExplain Codes Logo

Convert relative path to absolute using JavaScript

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Oct 3, 2024
TLDR

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:

let absoluteURL = new URL(relativePath, document.baseURI).href;

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:

let absolutePath = new URL('pics/puppy.jpg', 'http://cuteanimals.com/').href; // Result: 'http://cuteanimals.com/pics/puppy.jpg'

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 ".":

function absolutePath(base, relative) { var stack = base.split("/"), parts = relative.split("/"); stack.pop(); // Get rid of the breadcrumb trailing behind (or an empty string) // (Keeping in mind base is a directory path) for (var i = 0; i < parts.length; i++) { if (parts[i] === ".") // "Oh look, we're in the same place!" continue; if (parts[i] === "..") // "Back up, take a left at the last directory" stack.pop(); else // "Let's go through this back alley" stack.push(parts[i]); } return stack.join("/"); // "Follow this path directly to your destination. No U-turns allowed" }

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:

let dynamicAbsolutePath = absolutePath(document.baseURI, 'path/to/resource');

The safety net for bytecode blunders

Ensure your function doesn't trip over unexpected or invalid inputs:

if (!validInput(basePath, relativePath)) { return null; // "Sorry, can't help you get there. Try Google Maps?" }

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:

if (base.charAt(base.length - 1) !== '/') { base += '/'; //"Base, if you're going out, wear a slash!" }

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.