js实现转码
使用 encodeURIComponent 和 decodeURIComponent
encodeURIComponent 用于对 URI 组件进行编码,适用于 URL 参数部分。decodeURIComponent 用于解码。
const originalText = "Hello, 世界!";
const encodedText = encodeURIComponent(originalText); // "Hello%2C%20%E4%B8%96%E7%95%8C%21"
const decodedText = decodeURIComponent(encodedText); // "Hello, 世界!"
使用 btoa 和 atob(Base64)
btoa 将字符串编码为 Base64,atob 解码 Base64 字符串。注意:仅支持 ASCII 字符,非 ASCII 字符需先处理。

const text = "Hello, world!";
const encoded = btoa(text); // "SGVsbG8sIHdvcmxkIQ=="
const decoded = atob(encoded); // "Hello, world!"
// 处理非 ASCII 字符
const utf8Text = "你好";
const encodedUtf8 = btoa(encodeURIComponent(utf8Text)); // "JUU0JUJEJUEwJUU1JUE1JUJE"
const decodedUtf8 = decodeURIComponent(atob(encodedUtf8)); // "你好"
使用 TextEncoder 和 TextDecoder
处理 UTF-8 编码和解码,适用于现代浏览器。

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const text = "Hello, 世界!";
const encodedArray = encoder.encode(text); // Uint8Array
const decodedText = decoder.decode(encodedArray); // "Hello, 世界!"
处理 URL 编码的哈希或路径
encodeURI 和 decodeURI 用于完整 URL 编码,不编码特殊字符(如 /, :)。
const url = "https://example.com/路径?q=查询";
const encodedUrl = encodeURI(url); // "https://example.com/%E8%B7%AF%E5%BE%84?q=%E6%9F%A5%E8%AF%A2"
const decodedUrl = decodeURI(encodedUrl); // 原始 URL
处理二进制数据(如 ArrayBuffer)
通过 Uint8Array 和 String.fromCharCode 转换二进制数据。
// 字符串转 ArrayBuffer
function stringToArrayBuffer(str) {
const encoder = new TextEncoder();
return encoder.encode(str).buffer;
}
// ArrayBuffer 转字符串
function arrayBufferToString(buffer) {
const decoder = new TextDecoder();
return decoder.decode(new Uint8Array(buffer));
}
const buffer = stringToArrayBuffer("ABC");
const str = arrayBufferToString(buffer); // "ABC"
注意事项
encodeURIComponent编码范围更广,适合 URL 参数。- Base64 编码可能增加数据体积,但适合二进制数据或简单加密。
- 非 ASCII 字符需结合
encodeURIComponent和 Base64 处理。 - 现代浏览器推荐使用
TextEncoder/TextDecoder处理 UTF-8。






