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 使用
const str = 'test'
const encode = btoa(encodeURIComponent(str))
console.log(encode)
const str = 'dGVzdA=='
const decode = decodeURIComponent(atob(str))
console.log(decode)
- Chinese garbled processing method:
const Base64 = {
encode(str) {
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("一颗不甘坠落的流星");
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
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('一颗不甘坠落的流星'))
console.log(base64ToStr('5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif'))