Skip to content

Instantly share code, notes, and snippets.

@Hyvi
Created November 9, 2011 06:23
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Hyvi/1350603 to your computer and use it in GitHub Desktop.
Save Hyvi/1350603 to your computer and use it in GitHub Desktop.
/**
* 遗留的问题: 这是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