// Base64 编码示例
// 将字符串转换为 Base64 编码
function encodeBase64(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
// 示例:编码一个字符串
let originalString = "Hello, World!";
let encodedString = encodeBase64(originalString);
console.log("Encoded String:", encodedString);
// 将 Base64 编码的字符串解码回原始字符串
function decodeBase64(base64Str) {
return decodeURIComponent(Array.prototype.map.call(atob(base64Str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
// 示例:解码 Base64 字符串
let decodedString = decodeBase64(encodedString);
console.log("Decoded String:", decodedString);
encodeBase64 函数:
str 转换为 Base64 编码。btoa 函数进行 Base64 编码,但在此之前需要先使用 encodeURIComponent 处理特殊字符,以确保正确编码。decodeBase64 函数:
atob 函数进行 Base64 解码,然后通过 decodeURIComponent 恢复原始字符。示例:
"Hello, World!" 并输出编码后的结果。上一篇:js base64编码
下一篇:js 生成随机数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站