Course contentsShow
← JavaScript
Lesson 2361 of 2,72348. Working with Binary DataFree lesson

URL-Safe Base64 Variants

Learn about base64url encoding that replaces + and / with - and _ for safe use in URLs and filenames.

URL-Safe Base64 Variants

You'll learn how to adapt Base64 encoding for safe use in URLs and filenames by replacing problematic characters.

The Problem with Standard Base64

Standard Base64 uses the alphabet A-Z, a-z, 0-9, plus two special characters: + and /. Unfortunately, these special characters have meaning in URLs:

  • The + character in URLs represents a space (in query strings)
  • The / character is a path separator

If you try embedding standard Base64 in a URL or filename, these characters can cause parsing errors or unexpected behavior.

The URL-Safe Solution

Base64url (also called "URL-safe Base64") solves this by making two simple substitutions:

  • Replace + with - (hyphen)
  • Replace / with _ (underscore)

Both - and _ are safe in URLs and filenames without escaping.

Manual Conversion Example

// Standard Base64 string
const standard = "Hello+World/Test==";

// Convert to URL-safe
const urlSafe = standard
  .replace(/\+/g, '-')
  .replace(/\//g, '_');

console.log(urlSafe); // "Hello-World_Test=="

// Convert back to standard
const backToStandard = urlSafe
  .replace(/-/g, '+')
  .replace(/_/g, '/');

console.log(backToStandard); // "Hello+World/Test=="

Optional Padding Removal

Some implementations also remove the = padding characters (safe to do if the decoder knows to add them back based on length).

const noPadding = urlSafe.replace(/=+$/, '');
console.log(noPadding); // "Hello-World_Test"

Key Takeaway: URL-safe Base64 replaces + with - and / with _ to avoid special character conflicts in URLs and filenames—a simple character swap that prevents encoding headaches.