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

js base64 中文

作者:〖掉望   发布日期:2025-02-14   浏览:41

// 将中文字符串转换为 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);

解释说明:

  1. encodeBase64 函数:将中文字符串转换为 Base64 编码。由于 JavaScript 的 btoa 函数只能处理 ASCII 字符串,因此需要先将中文字符串转换为 UTF-8 编码,然后再进行 Base64 编码。

  2. decodeBase64 函数:将 Base64 编码的字符串解码为中文字符串。首先使用 atob 函数解码 Base64,然后将 UTF-8 编码的字符串转换回中文字符串。

  3. 示例:演示了如何对中文字符串进行 Base64 编码和解码,并输出结果。

上一篇:js file转base64

下一篇:js base64转图片

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

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

Laravel 中文站