计算字符串字节长度
编写方法计算字符串的字节长度,区分中英文字符
问题
编写一个方法,计算字符串的字节长度。假设英文字符占 1 个字节,中文字符占 2 个字节。
解答
方法一:遍历判断字符编码
function getByteLength(str) {
let length = 0;
for (let i = 0; i < str.length; i++) {
// charCodeAt 返回字符的 Unicode 编码
// ASCII 字符编码范围是 0-127
if (str.charCodeAt(i) > 127) {
length += 2; // 非 ASCII 字符算 2 个字节
} else {
length += 1; // ASCII 字符算 1 个字节
}
}
return length;
}
// 测试
console.log(getByteLength('hello')); // 5
console.log(getByteLength('你好')); // 4
console.log(getByteLength('hello你好')); // 9
方法二:正则替换
function getByteLength(str) {
// 将非 ASCII 字符替换为两个占位符,再计算长度
return str.replace(/[^\x00-\x7f]/g, 'aa').length;
}
// 测试
console.log(getByteLength('hello')); // 5
console.log(getByteLength('你好')); // 4
console.log(getByteLength('hello你好')); // 9
方法三:使用 TextEncoder(UTF-8 真实字节)
function getByteLength(str) {
// TextEncoder 默认使用 UTF-8 编码
// UTF-8 中,中文字符占 3 个字节
return new TextEncoder().encode(str).length;
}
// 测试
console.log(getByteLength('hello')); // 5
console.log(getByteLength('你好')); // 6 (UTF-8 中每个中文 3 字节)
console.log(getByteLength('hello你好')); // 11
方法四:使用 Blob
function getByteLength(str) {
// Blob 默认使用 UTF-8 编码
return new Blob([str]).size;
}
// 测试
console.log(getByteLength('hello')); // 5
console.log(getByteLength('你好')); // 6
console.log(getByteLength('hello你好')); // 11
关键点
charCodeAt()返回字符的 Unicode 编码,ASCII 字符范围是 0-127- 方法一和方法二适用于「中文 2 字节」的业务场景(如数据库字段限制)
- 方法三和方法四计算的是 UTF-8 真实字节长度(中文 3 字节)
\x00-\x7f是 ASCII 字符的十六进制范围- 根据实际业务需求选择合适的计算方式
目录