[JS] Realize Base64 encoding and decoding (and Chinese garbled problem)

1. Native implementation

  • JavaScript defines two global methods related to Base64.
1. btoa():字符串或二进制值转为 Base64 编码。
2. atob():把 Base64 编码转为原来的字符。
  • When encountering Chinese encoding, you need to do URI component encoding first or URI decoding the decoded content
1. encodeURIComponent():结合 btoa 使用
2. decodeURIComponent():结合 atob 使用
  • Example: Base64 encoding
// btoa() 相当于 window.btoa(),encodeURIComponent 同理
const str = 'test'
const encode = btoa(encodeURIComponent(str))
console.log(encode)	// dGVzdA==
  • Example: Base64 decoding
// atob() 相当于 window.atob(),decodeURIComponent 同理
const str = 'dGVzdA=='
const decode = decodeURIComponent(atob(str))
console.log(decode)	// test
  • Chinese garbled processing method:
const Base64 = {
    
    
    encode(str) {
    
    
        // 首先,我们使用 encodeURIComponent 来获得百分比编码的UTF-8,然后我们将百分比编码转换为原始字节,最后存储到btoa里面
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
            function toSolidBytes(match, p1) {
    
    
                return String.fromCharCode(Number('0x' + p1));
            }));
    },
    decode(str) {
    
    
        // 过程:从字节流到百分比编码,再到原始字符串
        return decodeURIComponent(atob(str).split('').map(function (c) {
    
    
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    }
}
let encoded = Base64.encode("一颗不甘坠落的流星"); 	// "5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif"
let decoded = Base64.decode(encoded); 				// "一颗不甘坠落的流星"

Second, plug-in implementation

  • According to the Base64 plug-in: codec: js-base64, determine whether it is in Base64 encoding format:is-base64
npm i js-base64
npm i is-base64
  • plug-in use
import isBase64 from 'is-base64';
import {
    
     Base64 } from 'js-base64';

// 封装解码函数
const base64ToStr = (base64Str: string): string => {
    
    
  if (isBase64(base64Str)) {
    
    
    return Base64.decode(base64Str);
  }
  return base64Str;
};
// 封装编码函数
export const strToBase64 = (str: string): string => Base64.encode(str);

console.log(strToBase64('一颗不甘坠落的流星'))	// 5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif
console.log(base64ToStr('5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif'))	// 一颗不甘坠落的流星

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/131070535