Skip to content

Instantly share code, notes, and snippets.

@vshmoylov
Created November 20, 2022 10:41
Show Gist options
  • Save vshmoylov/e9d9575a2846cc978f2d8bc72a9e802a to your computer and use it in GitHub Desktop.
Save vshmoylov/e9d9575a2846cc978f2d8bc72a9e802a to your computer and use it in GitHub Desktop.
base64UrlEncode and base64UrlDecode functions in JS/TS
/*
Basically, base64URL is a modification of common base64 standard containing following changes:
* Replaces "+" by "-" (minus)
* Replaces "/" by "_" (underline)
* Does not require a padding character
* Forbids line separators
Considering above, base64url string may be safely used as part of the URL without any further encoding.
For more details please see https://base64.guru/standards/base64url
*/
function base64UrlEncode(data: string): string {
return btoa(data).replace(/=+$/,'').replace(/\+/g,'-').replace(/\//g,'_');
}
function base64UrlDecode(data: string): string {
return atob(data.replace(/-/g,'+').replace(/_/g,'/'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment