js如何计算字符串的字节数

如果计算字符长度只需要使用length,
let str = "hello世界";
console.log(str.length)//7

如何计算所占用的字节数呢?

function getByteLength(str) {  
            let length = 0;  
            for (let i = 0; i < str.length; i++) {  
                let charCode = str.charCodeAt(i);  
                if ((charCode >= 0x0001 && charCode <= 0x007F) || (charCode >= 0x02B9 && charCode <= 0x036F)) {  
                    length += 1;  
                } else {  
                    length += 2;  
                }  
            }  
            return length;  
}
let str =
"hello世界";
console.log(getByteLength(str))//9

可能你会遇到这种类似的需求,可以用到(一个汉字占2个字节,一个数字和英文占1个字节)

 

posted on 2023-11-23 11:43  久居我梦  阅读(159)  评论(0编辑  收藏  举报

导航