如何在原生JavaScript中为TextEncoder指定所需字符编码?或获取指定编码的字符码?
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
- We create a
TextDecoderinstance configured foribm866. - We loop through every possible byte value (0 to 255, since CP866 uses single bytes).
- For each byte, we decode it to a character using the decoder.
- 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

