window.atob lost spaces bug All In One


window.atob lost spaces bug All In One

转换成 Base64 字符串后,丢失空格 ?







https://www.cnblogs.com/xgqfrms/p/16034483.html#5031829

encodeURIComponent / encodeURI

unescape / escape

const str = `Abc Xyz`;

encodeURIComponent(str);
// 'Abc%20Xyz'
window.btoa(encodeURIComponent(str));
// 'QWJjJTIwWHl6'
decodeURIComponent(window.atob( 'QWJjJTIwWHl6'));
//'Abc Xyz' ?
decodeURIComponent(window.atob(window.btoa(encodeURIComponent(str))));
// 'Abc Xyz' ?

unescape(encodeURIComponent(str));
// 'Abc Xyz'
window.btoa(unescape(encodeURIComponent(str)));
// 'QWJjIFh5eg=='
decodeURIComponent(escape(window.atob('QWJjIFh5eg==')));
// 'Abc Xyz' ?
decodeURIComponent(escape(window.atob(window.btoa(unescape(encodeURIComponent(str))))));
// 'Abc Xyz' ?

atob & btoa

window.atob;
//? atob() { [native code] }
atob;
//? atob() { [native code] }
window.atob === atob;
//true

atob(btoa('Vue3 script setup pass props'));
// 'Vue3 script setup pass props'

const str = btoa('Vue3 script setup pass props');
// 'VnVlMyBzY3JpcHQgc2V0dXAgcGFzcyBwcm9wcw=='
atob(str);
// 'Vue3 script setup pass props'

? b === binary string (Base64-decoded)

? a === ASCII string (Base64-encoded)

Base64-encoded ASCII string from a binary string

The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a String object in which each character in the string is treated as a byte of binary data).

btoa() 方法从二进制字符串(即,字符串中的每个字符都被视为二进制数据字节的 String 对象)创建 Base64 编码的 ASCII 字符串。

https://developer.mozilla.org/en-US/docs/Web/API/btoa

decodes Base64 encoding string

The atob() function decodes a string of data which has been encoded using Base64 encoding.

atob() 函数对已使用 Base64 编码的数据字符串进行解码。

https://developer.mozilla.org/en-US/docs/Web/API/atob

solution

function encodeBase64(str = '') {
   return window.btoa(unescape(encodeURIComponent(str)));
}

function decodeBase64(str = '') {
   return decodeURIComponent(escape(window.atob(str)));
}

refs

https://developer.mozilla.org/en-US/docs/Glossary/Base64

https://stackoverflow.com/a/62537645/5934465


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!