使用TextEncoder和TextDecoder

TextEncoder

编码:字符串 -> UTF-8字节流

const encoder = new TextEncoder()
const view = encoder.encode('€')
console.log(view); // Uint8Array(3) [226, 130, 172]

TextDecoder

解码: UTF-8字节流  -> 字符串

let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'

let u8arr = new Uint8Array([240, 160, 174, 183]);
let i8arr = new Int8Array([-16, -96, -82, -73]);
let u16arr = new Uint16Array([41200, 47022]);
let i16arr = new Int16Array([-24336, -18514]);
let i32arr = new Int32Array([-1213292304]);

console.log(utf8decoder.decode(u8arr));
console.log(utf8decoder.decode(i8arr));
console.log(utf8decoder.decode(u16arr));
console.log(utf8decoder.decode(i16arr));
console.log(utf8decoder.decode(i32arr));

 

例子:Utf-16 -> Utf-8

function Utf16ToUtf8(utf16String) {
  if (!utf16String) {
    return;
  }
  const encoder = new TextEncoder();
  const utf8Array = encoder.encode(utf16String); // 将UTF-16字符串编码为包含UTF-8表示的Uint8Array
  const decoder = new TextDecoder("utf-8"); // 创建一个具有“utf-8”编码的TextDecoder对象
  const utf8String = decoder.decode(utf8Array); // 将Uint8Array解码回utf-8字符串
  return utf8String;
}

 例子:Uint8Array转为String

let uint8array = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]); // "Hello World" in ASCII
let string = new TextDecoder("utf-8").decode(uint8array); // 创建一个新的TextDecoder对象,并使用其解码方法将Uint8Array转换为字符串
console.log(string); // Outputs: "Hello World"

注意,Internet Explorer不支持TextDecoder

如果需要支持Internet Explorer,则可能需要使用polyfill或其他方法将Uint8Array转换为字符串。such as [text-encoding]

npm install --save text-encoding
var TextDecoder = require('text-encoding').TextDecoder;
var uint8array = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
var string = new TextDecoder("utf-8").decode(uint8array);
console.log(string);  // "Hello World"

 

posted @ 2023-06-28 14:19  litiyi  阅读(1405)  评论(0编辑  收藏  举报