Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

后端 未结 10 2079
野趣味
野趣味 2020-11-22 16:24

I\'m using the Javascript window.atob() function to decode a base64-encoded string (specifically the base64-encoded content from the GitHub API). Problem is I\'

10条回答
  •  轮回少年
    2020-11-22 16:42

    The complete article that works for me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

    The part where we encode from Unicode/UTF-8 is

    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"
    

    This is one of the most used methods nowadays.

提交回复
热议问题