js判断字符串长度

https://www.cnblogs.com/hello321/p/7821400.html

var font_num= {};
font_num.get_length = function(str) {
  //获得字符串实际长度,中文2,英文1
  //要获得长度的字符串
  var realLength = 0, len = str.length, charCode = -1;
  for (var i = 0; i < len; i++) {
    charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) 
       realLength += 1;
    else
       realLength += 2;
  }
  return realLength;
};

alert(font_num.get_length('测试测shi,,,));

 

posted @ 2019-07-19 12:33  ThisCall  阅读(6581)  评论(0编辑  收藏  举报