js 计算输入框的字节数

来源:互联网 发布:清华 王奇 知乎 编辑:程序博客网 时间:2024/06/06 05:03
<html><head><script language="javascript">function  alertLength(){var name = document.main.name.value;window.alert("输入文字:【" + name + "】");var length = countLength(name);window.alert("字节数:" + length);}function countLength(str) {     var r = 0;     for (var i = 0; i < str.length; i++) {         var c = str.charCodeAt(i);         // Shift_JIS: 0x0 ~ 0x80, 0xa0 , 0xa1 ~ 0xdf , 0xfd ~ 0xff         // Unicode : 0x0 ~ 0x80, 0xf8f0, 0xff61 ~ 0xff9f, 0xf8f1 ~ 0xf8f3         if ( (c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {             r += 1;         } else {             r += 2;         }     }     return r; } </script></head><body><form name="main"><input type="text" name="name"><input type="button" onClick="alertLength()"></form></body></html>
  原文
0 0