window.btoa/window.atob

Summary

Creates a base-64 encoded ASCII string from a "string" of binary data.

Please note that this is not suitable for raw Unicode strings! See Unicode section below.

Syntax

var encodedData = window.btoa(stringToEncode);

Example

var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string
 
 

Notes

You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the window.atob method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

btoa() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

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:

function utf8_to_b64( str ) {
    return window.btoa(decodeURI(encodeURIComponent( str )));
}

function b64_to_utf8( str ) {
    return decodeURIComponent(encodeURI(window.atob( str )));
}

// Usage:
utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
  
  

A better, more faithful and less expensive solution is to convert the DOMString to a UTF-8 encoded string passing for typed arrays. In order to do this, please, read this paragraph.

Specification

DOM Level 0. Not part of any standard. Except of course http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#atob


From: https://developer.mozilla.org/zh-CN/docs/DOM/window.btoa





  1. // 完整的utf8字符串base64编码与解码
  2.  
  3. function uft8ToBase64(utf8) {
  4. return btoa(encodeURIComponent(utf8));
  5. }
  6.  
  7. function base64ToUtf8(base64) {
  8. return decodeURIComponent(atob(base64));
  9. }
  10.  
  11. var base64 = uft8ToBase64("hello @云淡然");
  12. // "aGVsbG8lMjAlNDAlRTQlQkElOTElRTYlQjclQTElRTclODQlQjY="
  13.  
  14. base64ToUtf8(base64);
  15. // "hello @云淡然"

  1. // 完整的utf8字符串base64编码与解码
  2.  
  3. function uft8ToBase64(utf8) {
  4. return btoa(encodeURIComponent(utf8));
  5. }
  6.  
  7. function base64ToUtf8(base64) {
  8. return decodeURIComponent(atob(base64));
  9. }
  10.  
  11. var base64 = uft8ToBase64("hello @云淡然");
  12. // "aGVsbG8lMjAlNDAlRTQlQkElOTElRTYlQjclQTElRTclODQlQjY="
  13.  
  14. base64ToUtf8(base64);
  15. // "hello @云淡然"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值