I have an AJAX call getting info out of the Github API. It is returned in base64 encoding but when i try to decode it I get the aforementioned error.
Has anyone run
atob breaks due to the newlines in the response. Remove them to get your code to work:
function addSVGToPage(SVGToAdd) {
var entry, decodedEntry; // <-- What is this doing here? It's unused.
makeAJAXCall(SVGToAdd, function (returnedJSON) {
console.info(window.atob(returnedJSON.data.content.replace(/\s/g, '')));
// ^^^^^^^^^^^^^^^^^^^
});
}
I have a better solution here:
live demo: https://codepen.io/arliang/pen/mNQayE?editors=1111
// https://best33.com/311.moe
function base64encode(str) {
let encode = encodeURIComponent(str).replace(/%([a-f0-9]{2})/gi, (m, $1) => String.fromCharCode(parseInt($1, 16)))
return btoa(encode)
}
function base64decode(str) {
let decode = atob(str).replace(/[\x80-\uffff]/g, (m) => `%${m.charCodeAt(0).toString(16).padStart(2, '0')}`)
return decodeURIComponent(decode)
}
function tests() {
Array.from([
/*鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪*/
'
According to MDN docs, you might need to escape
and then decodeURIComponent
to handle unicode:
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"