// 将中文字符串转换为 Base64 编码
function encodeBase64(str) {
// 先将中文字符串转为 UTF-8 编码,再进行 Base64 编码
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
// 将 Base64 编码的字符串解码为中文字符串
function decodeBase64(base64) {
// 先将 Base64 解码,再将 UTF-8 编码的字符串转为中文字符串
return decodeURIComponent(Array.prototype.map.call(atob(base64), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
// 示例
let originalString = "你好,世界";
let encodedString = encodeBase64(originalString);
console.log("Base64 编码后的字符串:", encodedString);
let decodedString = decodeBase64(encodedString);
console.log("Base64 解码后的字符串:", decodedString);
encodeBase64
函数:将中文字符串转换为 Base64 编码。由于 JavaScript 的 btoa
函数只能处理 ASCII 字符串,因此需要先将中文字符串转换为 UTF-8 编码,然后再进行 Base64 编码。
decodeBase64
函数:将 Base64 编码的字符串解码为中文字符串。首先使用 atob
函数解码 Base64,然后将 UTF-8 编码的字符串转换回中文字符串。
示例:演示了如何对中文字符串进行 Base64 编码和解码,并输出结果。
上一篇:js file转base64
下一篇:js base64转图片
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站