JS计算字符串的字节长度

String.prototype.byteLen = function(){

  var len = 0,

  i = this.length;

  while(i--)

  {

  len += (this.charCodeAt(i)>255 ? 2 : 1);

  }

  return len;

};

 ("中国").byteLen(); //会返回4

  ("abc").byteLen(); //会返回3

你可能感兴趣的:(字符串)