Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js base64 编码

作者:狂刀血斧   发布日期:2026-05-25   浏览:111

// 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);

解释说明:

  1. encodeBase64 函数:

    • 该函数将输入的字符串 str 转换为 Base64 编码。
    • 使用 btoa 函数进行 Base64 编码,但在此之前需要先使用 encodeURIComponent 处理特殊字符,以确保正确编码。
  2. decodeBase64 函数:

    • 该函数将 Base64 编码的字符串解码回原始字符串。
    • 使用 atob 函数进行 Base64 解码,然后通过 decodeURIComponent 恢复原始字符。
  3. 示例:

    • 编码字符串 "Hello, World!" 并输出编码后的结果。
    • 解码 Base64 编码的字符串并输出解码后的结果。

上一篇:js base64编码

下一篇:js 生成随机数

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站