Skip to content

Instantly share code, notes, and snippets.

@kenany
Created April 10, 2012 20:38
Show Gist options
  • Save kenany/2354298 to your computer and use it in GitHub Desktop.
Save kenany/2354298 to your computer and use it in GitHub Desktop.
base64 in JavaScript
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
Modernizr.load({
test: window.btoa && window.atob,
nope: 'base64.js',
complete: function () {
var encodedData = utf8_to_b64("Hello, world"); // encode a string
var decodedData = b64_to_utf8(encodedData); // decode the string
}
});
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
Modernizr.load({
test: window.btoa && window.atob,
nope: 'base64.js',
complete: function () {
// `btoa` and `atob` are now safe to use
}
});
yepnope({
test: window.btoa && window.atob,
nope: 'base64.js',
callback: function () {
// `btoa` and `atob` are now safe to use
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment