javascript 中字符串编码转换主要依赖 encodeuricomponent、decodeuricomponent 和 atob/btoa。前者用于 url 安全编码,后者用于 base64 编解码。

URL 参数中的特殊字符如何安全编码
使用 encodeURIComponent 将字符串转为 URL 安全的格式,它会转义除字母数字外的所有字符。例如空格变为 %20,中文变为 UTF-8 字节序列的十六进制表示。

const str = "hello world & test"; const encoded = encodeURIComponent(str); console.log(encoded); // "hello%20world%20%26%20test" const decoded = decodeURIComponent(encoded); console.log(decoded); // "hello world & test"
预期结果:
encoded: "hello%20world%20%26%20test"
decoded: "hello world & test"
立即学习“Java免费学习笔记(深入)”;
Base64 编码与解码如何实现
使用 btoa 将字符串转为 Base64 编码,atob 将其还原。注意 btoa 仅支持 ASCII 字符,非 ASCII 需先通过 encodeURIComponent 处理。

const str = "Hello!"; const base64 = btoa(str); console.log(base64); // "SGVsbG8h" const original = atob(base64); console.log(original); // "Hello!"
预期结果:
base64: "SGVsbG8h"
original: "Hello!"
中文在 Base64 编码中会出错吗
直接对中文字符串调用 btoa 会抛出 InvalidCharacterError,因为 btoa 只接受 ASCII 范围字符。必须先使用 encodeURIComponent 将中文转为百分号编码,再对结果进行 Base64 编码。


















