一、原生實現(xiàn)
- JavaScript 定義了兩個與 Base64 相關(guān)的全局方法。
1. btoa():字符串或二進制值轉(zhuǎn)為 Base64 編碼。
2. atob():把 Base64 編碼轉(zhuǎn)為原來的字符。
- 遇到中文編碼需要先做一次 URI 組件編碼或?qū)獯a后的內(nèi)容進行 URI 解碼
1. encodeURIComponent():結(jié)合 btoa 使用
2. decodeURIComponent():結(jié)合 atob 使用
- 示例:Base64 編碼
// btoa() 相當于 window.btoa(),encodeURIComponent 同理
const str = 'test'
const encode = btoa(encodeURIComponent(str))
console.log(encode) // dGVzdA==
- 示例:Base64 解碼
// atob() 相當于 window.atob(),decodeURIComponent 同理
const str = 'dGVzdA=='
const decode = decodeURIComponent(atob(str))
console.log(decode) // test
- 中文亂碼處理方法:
const Base64 = {
encode(str) {
// 首先,我們使用 encodeURIComponent 來獲得百分比編碼的UTF-8,然后我們將百分比編碼轉(zhuǎn)換為原始字節(jié),最后存儲到btoa里面
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode(Number('0x' + p1));
}));
},
decode(str) {
// 過程:從字節(jié)流到百分比編碼,再到原始字符串
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); // "一顆不甘墜落的流星"
二、插件實現(xiàn)
- 按照 Base64 插件:編解碼:
js-base64
,判斷是否是Base64編碼格式:is-base64
npm i js-base64
npm i is-base64
- 插件使用
import isBase64 from 'is-base64';
import { Base64 } from 'js-base64';
// 封裝解碼函數(shù)
const base64ToStr = (base64Str: string): string => {
if (isBase64(base64Str)) {
return Base64.decode(base64Str);
}
return base64Str;
};
// 封裝編碼函數(shù)
export const strToBase64 = (str: string): string => Base64.encode(str);
console.log(strToBase64('一顆不甘墜落的流星')) // 5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif
console.log(base64ToStr('5LiA6aKX5LiN55SY5Z2g6JC955qE5rWB5pif')) // 一顆不甘墜落的流星
文章來源地址http://www.zghlxwxcb.cn/news/detail-615055.html
文章來源:http://www.zghlxwxcb.cn/news/detail-615055.html
到了這里,關(guān)于【JS】實現(xiàn) Base64 編碼和解碼(及中文亂碼問題)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!