Created
November 20, 2022 10:41
-
-
Save vshmoylov/e9d9575a2846cc978f2d8bc72a9e802a to your computer and use it in GitHub Desktop.
base64UrlEncode and base64UrlDecode functions in JS/TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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