计算字节数

2019-12-11  本文已影响0人  晴天M雨天

<script type="text/javascript">
var str="a";//依次输入单个英文字符、英文标点、中文、中文标点测试单个字符占的字节数
function byteLength(s) {
    var totalLength = 0;
    var i;
    var charCode;
    for (i = 0; i < s.length; i++) {
     charCode = s.charCodeAt(i);
     if (charCode < 0x007f) {
      totalLength = totalLength + 1;
     } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
      totalLength += 2;
     } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
      totalLength += 3;
     }
    }
    return totalLength;
   }
alert(byteLength(str));
</script>

上一篇下一篇

猜你喜欢

热点阅读