Skip to content

Instantly share code, notes, and snippets.

@osuritz
Created October 21, 2022 03:21
Show Gist options
  • Save osuritz/179704b97f00e2220e185b1b0a033906 to your computer and use it in GitHub Desktop.
Save osuritz/179704b97f00e2220e185b1b0a033906 to your computer and use it in GitHub Desktop.
URL-Safe Base64 encode/decode in TypeScript/JavaScript
/** Returns a Base64-encoded string is safe to embed in URLs. */
function base64UrlEncode(str: string) {
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
/**
* Deocdes a string of URL-safe, Base64-encoded data into bytes, and encodes
* those bytes into a string using Latin-1 (ISO-8859-1).
*
* The input data is typically encoded with a `base64UrlEncode` method.
* @param val The URL-safe, Base64-encoded input string.
* @returns The decoded string.
*/
function base64UrlDecode(base64str: string): string {
return atob(base64str.replace(/-/g, '+').replace(/_/g, '/'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment