You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在原生JavaScript中为TextEncoder指定所需字符编码?或获取指定编码的字符码?

Get CP866 Character Codes with Native JavaScript

You’re right to call out that TextEncoder only supports UTF-8—any encoding parameter you pass gets ignored (it’s not part of the standard API). The good news is we can use TextDecoder (which does support encodings like ibm866) in a clever way to get the byte value for a given character without relying on pre-built arrays or external services.

Solution: Sync Function Using TextDecoder

Since CP866 is a single-byte encoding (each character maps to exactly one byte between 0-255), we can iterate through all possible byte values and check which one decodes to your target character:

function getByteForCharInEncoding(char, encoding) {
  const decoder = new TextDecoder(encoding);
  // Iterate through all possible byte values (0-255)
  for (let byteValue = 0; byteValue < 256; byteValue++) {
    const byteBuffer = new Uint8Array([byteValue]);
    if (decoder.decode(byteBuffer) === char) {
      return byteValue;
    }
  }
  // Return null if the character isn't present in the encoding
  return null;
}

// Example usage for 'А' in CP866
console.log(getByteForCharInEncoding('А', 'ibm866')); // Output: 192

How This Works

  1. We create a TextDecoder instance configured for ibm866.
  2. We loop through every possible byte value (0 to 255, since CP866 uses single bytes).
  3. For each byte, we decode it to a character using the decoder.
  4. When we find the byte that decodes to our target character, we return its value.

This is pure native JavaScript, no external dependencies or pre-defined arrays required. It works for any single-byte encoding supported by your browser’s TextDecoder implementation (most modern browsers support ibm866 out of the box).

Notes

  • If you need to encode entire strings instead of single characters, you could extend this function to process each character in the string and collect the corresponding bytes.
  • For multi-byte encodings, this approach won’t work, but since CP866 is single-byte, it’s a perfect fit.

内容的提问来源于stack exchange,提问作者repulsor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 08:12:42