Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

TextDecoder và TextEncoder trong JavaScript


TextEncoder mã hóa chuỗi thành Uint8Array (UTF-8). TextDecoder giải mã Uint8Array (hoặc buffer) thành chuỗi, hỗ trợ nhiều encoding: UTF-8, ISO-8859-2, KOI8-R, GBK...

Ví dụ

Mã hóa chuỗi "Hello world" và giải mã mảng byte [119, 111, 114, 108, 100] ("world"):

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>TextEncoder & TextDecoder</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; color: rebeccapurple; }
    .result { color: red; }
  </style>
</head>
<body>
  <h1>TextDecoder và TextEncoder trong JavaScript</h1>
  <div class="sample"></div>
  <button class="Btn">MÃ HÓA CHUỖI</button>
  <div class="result"></div>
  <h3>Nhấn để mã hóa chuỗi "Hello world"</h3>
  <div class="sample"></div>
  <button class="Btn">GIẢI MÃ CHUỖI</button>
  <div class="result"></div>
  <h3>Nhấn để giải mã Uint8Array [119,111,114,108,100]</h3>
  <script>
    const btns = document.querySelectorAll(".Btn");
    const samples = document.querySelectorAll(".sample");
    const results = document.querySelectorAll(".result");
    const str = "Hello world";
    const bytes = new Uint8Array([119, 111, 114, 108, 100]); // "world"
    samples[0].textContent = str;
    samples[1].textContent = bytes;
    btns[0].addEventListener("click", () => {
      const encoder = new TextEncoder();
      results[0].innerHTML += `Chuỗi đã mã hóa: ${encoder.encode(str)}<br>`;
    });
    btns[1].addEventListener("click", () => {
      const decoder = new TextDecoder();
      results[1].innerHTML += `Chuỗi đã giải mã: ${decoder.decode(bytes)}<br>`;
    });
  </script>
</body>
</html>

Kết quả

Mã hóa: Uint8Array(11) [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]. Giải mã: "world".

Ứng dụng: Xử lý stream dữ liệu nhị phân, WebSocket, đọc file binary, chuyển đổi encoding.