Created
November 9, 2011 06:23
-
-
Save Hyvi/1350603 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 遗留的问题: 这是utf-8 ?? | |
* 关于encodeURIComponent 与 encodeURI 的最佳实践 | |
* http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent | |
* | |
Unicode Strings | |
In most browsers, calling window.btoa on a Unicode string will cause a Character Out Of Range exception. | |
To avoid this, consider this pattern, noted by Johan Sundström | |
(http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html): | |
*/ | |
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment