JavaScript 将中文转换为 GBK 编码并获取长度
这个问题涉及到编码转换和字符串长度的问题,可以使用以下代码实现:
function convertToGBK(str) {
  const encoder = new TextEncoder('GBK');
  const bytes = encoder.encode(str);
  const length = bytes.length;
  return { bytes, length };
}
// 测试代码
const { bytes, length } = convertToGBK('中文');
console.log(bytes); // Uint8Array(4) [ 196, 223, 186, 195 ]
console.log(length); // 4
首先,我们使用 TextEncoder 对象将字符串转换为 GBK 编码的字节数组。然后,使用 length 属性获取字节数组的长度,即为字符串在 GBK 编码下的长度。最后,将字节数组和长度作为对象返回。
原文地址: https://www.cveoy.top/t/topic/oLmC 著作权归作者所有。请勿转载和采集!