欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算字节长度

程序员文章站 2024-02-26 15:39:52
...
function getLength(str){
  var n = str.length, c, s=0;
  while(n--){
    c=str.charCodeAt(n);
    switch(true){
      case c<=0x7F: s+=1; break;
      case c<=0x7FF: s+=2; break;
      case c<=0xFFFF: s+=3; break;
      case c<=0x1FFFF: s+=4; break;
      case c<=0x7FFFFFFFF: s+=5; break;
    }
  }
  return s;
}
console.log(getLength('สวัสดี'))