btoa(), atob() 支援中文的方法
Posted on May 14th, 2014
由於 btoa 只能以英文數字等非 unicode 組合作為輸入, 所以若要支援 unicode 字元(中文), 必須用替代方法, 先將內容 escape 再 encode,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function utf8_to_b64( str ) { | |
return window.btoa(encodeURIComponent( escape( str ))); | |
} | |
function b64_to_utf8( str ) { | |
return unescape(decodeURIComponent(window.atob( str ))); | |
} | |
// Usage: | |
utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ== | |
b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode" | |
utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ== | |
b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!" |
DEMO: [jsfiddle](http://jsfiddle.net/zrj9ydgc/)
REF: [window.btoa(MDN)](https://developer.mozilla.org/en-US/docs/Web/API/window.btoa)