Skip to content

Instantly share code, notes, and snippets.

@le0pard
Created October 11, 2021 12:55
Show Gist options
  • Save le0pard/5b90ee9569a3a9c5c14a9e5f8d007bdb to your computer and use it in GitHub Desktop.
Save le0pard/5b90ee9569a3a9c5c14a9e5f8d007bdb to your computer and use it in GitHub Desktop.
Base64 in browser with Unicode support (no deprecated 'unescape' and 'escape' functions)
const b64EncodeUnicode = (str) => (
window.btoa(window.encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_match, p1) => (
String.fromCharCode(`0x${p1}`)
)))
)
const b64DecodeUnicode = (str) => (
window.decodeURIComponent(window.atob(str).split('').map((c) => (
`%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`
)).join(''))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment