当前位置: 首页 > news >正文

js中 btoa 方法 和 atob方法介绍

在 JavaScript 中,btoa()atob() 是两个内置的 Base64 编码/解码 方法,用于在字符串与 Base64 编码之间相互转换。
它们的名字来源于:

  • btoa = binary to ASCII
  • atob = ASCII to binary

🧩 一、btoa() —— 将字符串编码为 Base64

📘 语法:

btoa(string)

📥 参数:

  • string:要进行编码的字符串(只能包含 Latin1 字符,即每个字符的代码点在 0x00 到 0xFF 之间)。

📤 返回值:

  • 返回该字符串的 Base64 编码形式

✅ 示例:

const str = "Hello World!";
const encoded = btoa(str);
console.log(encoded); // 输出: "SGVsbG8gV29ybGQh"

🧩 二、atob() —— 将 Base64 解码为字符串

📘 语法:

atob(encodedString)

📥 参数:

  • encodedString:Base64 格式的字符串。

📤 返回值:

  • 解码后的原始字符串。

✅ 示例:

const encoded = "SGVsbG8gV29ybGQh";
const decoded = atob(encoded);
console.log(decoded); // 输出: "Hello World!"

⚠️ 注意事项

1. btoa / atob 仅支持 Latin1(单字节字符)

这意味着它们 不能直接处理 UTF-8(例如中文、表情符号等)
如果直接编码中文,会报错或出现乱码:

btoa("你好"); // ❌ 报错:The string to be encoded contains characters outside of the Latin1 range.

✅ 正确做法:先将字符串转换为 UTF-8 字节,再编码

// 编码中文安全方式
const encoded = btoa(unescape(encodeURIComponent("你好")));
console.log(encoded); // 输出: "5L2g5aW9"// 解码中文安全方式
const decoded = decodeURIComponent(escape(atob(encoded)));
console.log(decoded); // 输出: "你好"

💡 三、现代替代方案(推荐用法)

在现代浏览器或 Node.js 中,推荐使用 TextEncoder / TextDecoderBuffer 来处理任意字符的 Base64 编码:

✅ 浏览器(现代 API):

const text = "你好世界";
const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(text)));
console.log(encoded); // 输出: "5L2g5aW977yM5LiW55WM"const decoded = new TextDecoder().decode(Uint8Array.from(atob(encoded), c => c.charCodeAt(0))
);
console.log(decoded); // 输出: "你好世界"

✅ Node.js 环境:

const text = "你好世界";
const encoded = Buffer.from(text, "utf-8").toString("base64");
console.log(encoded); // 输出: "5L2g5aW977yM5LiW55WM"const decoded = Buffer.from(encoded, "base64").toString("utf-8");
console.log(decoded); // 输出: "你好世界"

🧭 总结对比

方法功能仅支持 ASCII支持中文适用环境
btoa()字符串 → Base64✅ 是❌ 否浏览器
atob()Base64 → 字符串✅ 是❌ 否浏览器
Buffer双向转换❌ 否✅ 是Node.js
TextEncoder / TextDecoder双向转换❌ 否✅ 是浏览器 & Node.js(现代)
http://www.dtcms.com/a/478905.html

相关文章:

  • 做网络写手 哪个网站比较好亚马逊deal网站怎么做
  • css布局的几种方式
  • 前端数值运算精度丢失问题及解决方案
  • 免费建站软件有哪些苏州建行网站首页
  • 极海APM32F107V6 移植FreeRTOS+CMSIS-RTOS V2
  • Centos Stream 8 搭建Cas Server
  • 营销型网站建设优化汽车电商网站建设
  • 网站建设中最基本的决策南昌网站建设和推广
  • 网页设计网站如何添加链接家庭网站建设
  • ModuleNotFoundError: No module named ‘conda_token‘
  • 长春哪家做网站做的好网站建设员是做什么的
  • Milvus部署在T4 GPU上,Dify检索性能可以提升多少?
  • 南阳手机网站推广h5网页设计软件
  • 戴森球的物理模拟
  • 基于springboot社区养老服务平台的设计与实现(附源码)
  • 晨光科技 网站建设北京优化网站
  • 简易水位报警器方案开发案例
  • 公司网站建设费用计入什么科目做网站主页
  • 最长子串和分配苹果问题
  • Ubuntu设置共享文件夹
  • 网站开发一个多少钱系统网站推广方案怎么做
  • 制作网站需要懂哪些重生北京上大学开网吧做网站的小说
  • 二级域名iis建立网站免费企业邮箱排名
  • Linux程序设计从入门到实战(价值198元)课程下载
  • Leetcode 3709. Design Exam Scores Tracker
  • 告别环境配置难题:GISBox如何让DWG转GeoJSON零门槛上手
  • 国外网页网站设计如何修改wordpress登录页
  • 如需锦州网站建设网站备案前置审批表
  • 什么网站资源多东营最新通知
  • Docker图形化管理,轻松上手docker