JavaScript 获取中文字符串 GBK 编码长度
function getGBKLength(str) {
let bytesCount = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode <= 127) {
bytesCount += 1;
} else {
bytesCount += 2;
}
}
return bytesCount;
}
const chineseString = '你好,世界!';
const gbkLength = getGBKLength(chineseString);
console.log('${chineseString}' 的 GBK 编码长度为 ${gbkLength} 字节。);
原文地址: https://www.cveoy.top/t/topic/oLmM 著作权归作者所有。请勿转载和采集!