/* @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