Skip to content

Instantly share code, notes, and snippets.

@zackdouglas
Last active April 3, 2023 07:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackdouglas/d9e36168dadbba0762469290cae07c99 to your computer and use it in GitHub Desktop.
Save zackdouglas/d9e36168dadbba0762469290cae07c99 to your computer and use it in GitHub Desktop.
Universal JS atou/utoa

Utoatou

A better btoa and atob that supports non-ASCII characters in a healthy manner.

Compatible with AMD, CommonJS, and ES2015 module loaders.

;(function(global){
const Utoatou = function () {}
var utoa = s => global.btoa(global.unescape(global.encodeURIComponent(s)))
var atou = a => global.decodeURIComponent(global.escape(global.atob(a)))
var utoh = s => btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g,'');
var htou = h => atou(h.replace(/-/g,'+').replace(/_/g,'/'));
Utoatou.utoa = utoa;
Utoatou.atou = atou;
Utoatou.utoh = utoh;
Utoatou.htou = htou;
if (typeof define === 'function' && define.amd) {
define(function(){ return Utoatou })
}
else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Utoatou
}
} else {
global.Utoatou = Utoatou
}
}(this));
@sdjdd
Copy link

sdjdd commented Jun 9, 2021

- var utoh = s => btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g,'');
+ var utoh = s => utoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g,'');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment