Skip to content

Instantly share code, notes, and snippets.

@metaColin
Last active February 10, 2017 22:04
Show Gist options
  • Save metaColin/7ffc357f9be9683ef49b6c86df078666 to your computer and use it in GitHub Desktop.
Save metaColin/7ffc357f9be9683ef49b6c86df078666 to your computer and use it in GitHub Desktop.
toBase64 & fromBase64 functions for front end javascript
// grr why is base64 encoding not easier in frontend js?
var fromBase64 = function fromBase64(base64) {
var raw = window.atob(base64);
var rawLength = raw.length;
var ab = new ArrayBuffer(rawLength);
var array = new Uint8Array(ab);
for (var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return ab;
};
var toBase64 = function(ab) {
var raw = "";
var array = new Uint8Array(ab);
for (var i = 0; i < array.length; i++) {
raw = raw + String.fromCharCode(array[i]);
}
return window.btoa(raw);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment