<input name="tes1" value="输入判读字符"/>
<input type=button value='显示长度' onclick='alert( document.all.tes1.value.lenB())'>
<script>
String.prototype.lenB = function(){return this.replace(/[^\x00-\xff]/g,"**").length;} </script>

解决方案 »

  1.   

    javascript的String使用Unicode编码汉字占3 Byte 字母数字1 Byte
    如果数据库使用UTF-8编码
    可以用
    function getByteForUTF(s)
    {
    return encodeURIComponent(s).replace(/%[A-Z0-9]{2}/g,"0").length;
    }
    alert(getByteForUTF("像"));
    得到字节数乘号×的Unicode编码为
    <script>
    alert("×".charCodeAt(0));
    </script>
    215<255
    占1 Byte
      

  2.   

    Unicode(学名:UCS)使用全16位字符集,每个字符占两个字节(覆盖了美国,欧洲,中东,非洲,印度,亚洲和太平洋地区的语言)UTF-8(UCS Transformation Format:UCS转化格式)
    从Unicode  到  UTF-8 规则
    0000 - 007F 0xxxxxxx     使用1字节(前128个Unicode字符<两字节>对应ASCII字符部分<一字节>)
    0080 - 07FF 110xxxxx 10xxxxxx     使用2字节存储
    0800 - FFFF 1110xxxx 10xxxxxx 10xxxxxx    使用3字节存储
    GB2312 我国制定的汉字编码.兼容ASCII 一共收录了7445个字符,包括6763个汉字和682个其它符号
    00 - 7F 0xxxxxxx     使用1字节 (ASCII)
    其他                 使用2字节 其他符号和汉字例如乘号×
    Unicode的×:(00D7)2字节
    utf-8的×:因为(00D7)位于0080 - 07FF段,所以2字节
    GB2312的×:因为0xD7 > 0x7F 所以用2字节存所以
    使用utf-8的字节数
    function getByteForUTF(s)
    {
    a=s.replace(/[\u0000-\u007f]/g,"\u0061");
    b=a.replace(/[\u0080-\u07ff]/g,"\u0061\u0061");
    c=b.replace(/[\u0800-\uffff]/g,"\u0061\u0061\u0061");
    return c.length;
    }使用gb2312的字节数
    function getByteForGB(s)
    {
    return s.replace(/[^\u0000-\u007f]/g,"\u0061\u0061").length;
    }