function getGBKLength(str) { let totalLength = 0; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i); if (charCode <= 127) { totalLength += 1; } else { totalLength += 2; } } return totalLength; }

console.log(getGBKLength('中文')); // 4 console.log(getGBKLength('JavaScript')); // 10

JavaScript 计算中文GBK编码长度

原文地址: https://www.cveoy.top/t/topic/oLmN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录