1

I work with a backend service that sends me back base64 in plain text.

When I log it in the console, copy/paste in Base64Decode, I can see my string contains line break, this is what I want.

But when I use functions to convert this base64 string into UTF-8 one, break lines are lost.

What I tried :

function b64DecodeUnicode(str) {
  return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
       return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
   }).join(''))
}

This solution comes from here, but is not working.

Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
Zooly
  • 4,736
  • 4
  • 34
  • 54
  • Yeah, just to be clear, have you tried to set the result as `.textContent` of a `
    `?
    –  Nov 20 '18 at 10:00
  • Possible duplicate of [Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings](https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings) – Eugene Mihaylin Nov 20 '18 at 10:04

2 Answers2

1

Issue was that after decoding base64 to UTF-8, Line Feed chars (ASCII 10) are transformed into Carriage Return chars (ASCII 13).

I don't know why, maybe I am missing something in base64 decode.

Zooly
  • 4,736
  • 4
  • 34
  • 54
0

I tried solution from here with line break as \n, it works:

function b64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) 
  {
    return String.fromCharCode(parseInt(p1, 16))
   }))
}

function b64DecodeUnicode(str) {
  return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
  }).join(''))
}

console.log(b64DecodeUnicode(b64EncodeUnicode('✓ à la\nmo\nde')));
Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31