js文本 与 UTF-8 字节字符串 互转
时间:2025-7-9 15:04 作者:六度科技 分类: JS
方法1(现代浏览器):TextEncoder
+ TextDecoder
1. 正向转换:文本 → UTF-8 字节字符串
function textToUtf8ByteString(text) {
const encoder = new TextEncoder();
const utf8Bytes = encoder.encode(text);
return "{" + Array.from(utf8Bytes).join(",") + "}";
}
// 示例
const originalText = "你好";
const byteString = textToUtf8ByteString(originalText);
console.log(byteString); // 输出: {228,189,160,229,165,189}
2. 反向解析:字节字符串 → 文本
function utf8ByteStringToText(byteString) {
// 1. 移除 { },并按逗号分割成数组
const byteArray = byteString.slice(1, -1).split(",").map(Number);
// 2. 使用 TextDecoder 解码
const decoder = new TextDecoder("utf-8");
const uint8Array = new Uint8Array(byteArray);
return decoder.decode(uint8Array);
}
// 示例
const byteStr = "{228,189,160,229,165,189}";
const decodedText = utf8ByteStringToText(byteStr);
console.log(decodedText); // 输出: "你好"
方法2(兼容旧浏览器):encodeURIComponent
+ unescape
1. 正向转换:文本 → UTF-8 字节字符串
function textToUtf8ByteString(text) {
const escaped = encodeURIComponent(text);
const bytes = [];
for (let i = 0; i < escaped.length; i++) {
const char = escaped[i];
if (char === "%") {
// 提取 % 后面的 2 位 16 进制数(如 %E4 → 228)
const hex = escaped.substr(i + 1, 2);
bytes.push(parseInt(hex, 16));
i += 2;
} else {
// ASCII 字符直接取 charCode
bytes.push(char.charCodeAt(0));
}
}
return "{" + bytes.join(",") + "}";
}
// 示例
const originalText = "你好";
const byteString = textToUtf8ByteString(originalText);
console.log(byteString); // 输出: {228,189,160,229,165,189}
2. 反向解析:字节字符串 → 文本
function utf8ByteStringToText(byteString) {
// 1. 移除 { },并按逗号分割成数组
const byteArray = byteString.slice(1, -1).split(",").map(Number);
// 2. 将字节数组转为 % 编码字符串(如 228 → %E4)
let escaped = "";
for (const byte of byteArray) {
if (byte >= 128) {
escaped += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
} else {
escaped += String.fromCharCode(byte);
}
}
// 3. 使用 decodeURIComponent 解码
return decodeURIComponent(escaped);
}
// 示例
const byteStr = "{228,189,160,229,165,189}";
const decodedText = utf8ByteStringToText(byteStr);
console.log(decodedText); // 输出: "你好"
总结
功能 | 方法1(现代) | 方法3(兼容旧浏览器) |
---|---|---|
文本 → UTF-8 字节字符串 | TextEncoder |
encodeURIComponent + unescape |
UTF-8 字节字符串 → 文本 | TextDecoder |
decodeURIComponent |
适用环境 | 现代浏览器、Node.js | 旧浏览器、无 TextEncoder 环境 |
示例输入 | "你好" → {228,189,160,229,165,189} |
"你好" → {228,189,160,229,165,189} |
示例输出 | {228,189,160,229,165,189} → "你好" |
{228,189,160,229,165,189} → "你好" |
这样,无论是 现代浏览器 还是 旧环境,都可以实现 文本 ↔ UTF-8 字节字符串 的相互转换! 🚀