首页 > 其他分享 >计算字符串多少bytes方法

计算字符串多少bytes方法

时间:2023-03-07 18:44:24浏览次数:41  
标签:utf 计算 charset bytes len str 字符串 charCode String

/* @param  {String} str
 * @param  {String} charset utf-8, utf-16
 * @return {Number}
 */
var sizeof = function(str, charset){
    var total = 0,
        charCode,
        i,
        len;
    charset = charset ? charset.toLowerCase() : '';
    if(charset === 'utf-16' || charset === 'utf16'){
        for(i = 0, len = str.length; i < len; i++){
            charCode = str.charCodeAt(i);
            if(charCode <= 0xffff){
                total += 2;
            }else{
                total += 4;
            }
        }
    }else{
        for(i = 0, len = str.length; i < len; i++){
            charCode = str.charCodeAt(i);
            if(charCode <= 0x007f) {
                total += 1;
            }else if(charCode <= 0x07ff){
                total += 2;
            }else if(charCode <= 0xffff){
                total += 3;
            }else{
                total += 4;
            }
        }
    }
    return total;
}

  

标签:utf,计算,charset,bytes,len,str,字符串,charCode,String
From: https://www.cnblogs.com/wilsunson/p/17189138.html

相关文章