2012-08-28 16:50

js获取字符串的字节数

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;
  }
}

正则表达式检测字符串的字节长度:

var lenReg = function(str){
  return str.replace(/[^x00-xFF]/g,'**').length;
};

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

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

相关文章:

  • 2021-07-12
  • 2022-12-23
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-19
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2021-11-24
  • 2021-07-12
相关资源
相似解决方案