【JavaScript】UTF-8をbase64エンコード・デコードする (日本語対応)
btoa('a'); // 'YQ=='atob('YQ=='); // 'a'
btoa('あ'); // Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
- JavaScriptで文字列をbase64にエンコードする際は
window.btoa()
、デコードする際はwindow.atob()
で実現できる - しかし日本語のようにLatin1ではない文字だとエラーになる
日本語をエンコードする方法
function encode(str) { const charCodes = new TextEncoder().encode(str); return btoa(String.fromCharCode(...charCodes));}
function decode(str) { const utf8Array = Uint8Array.from( Array.from(atob(str)).map((s) => s.charCodeAt(0)), ); return new TextDecoder().decode(utf8Array);}
encode('あ'); // '44GC'decode('44GC'); // 'あ'