一、js获取字符串的字节数

这个好使---
function getBytesLength(str) {
// 在GBK编码里,除了ASCII字符,其它都占两个字符宽
return str.replace(/[^\x00-\xff]/g, 'xx').length;

}

用正则表达式检测所用的时间竟然是for循环的两倍!!!!

var lenFor = function(str){
  var byteLen=0,len=str.length;
  if(str){
    for(var i=0; i<len; i++){
      if(str.charCodeAt(i)>255){
        byteLen += 2;
      }
      else{
        byteLen++;
      }
    }
    return byteLen;
  }
  else{
    return 0;
  }
}

 

 

 

更多:

Javascript 字符串(一)常见函数使用

JavaScript数组(三)数组对象使用整理

JavaScript数组(二)实例

相关文章:

  • 2021-11-13
  • 2021-08-18
  • 2022-12-23
  • 2021-11-13
  • 2021-11-13
  • 2022-12-23
猜你喜欢
  • 2021-10-12
  • 2021-08-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案