js统计输入文字的字节数(byte)


这里主要考虑的是日文,日文中包含了半角和全角文字,半角算1,全角算2.

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM