function getCharacters(str) {
var totalByteLength = 0;
var i;
var charCode;
for (i = 0; i < str.length; i++) {
charCode = str.charCodeAt(i);
if (charCode < 0x007f) {//0x0000 - 0x007F:1字节
totalByteLength += 1;
} else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {//0x0080 - 0x07FF:2字节
totalByteLength += 2;
} else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {//0x0800 - 0xFFFF:3字节
totalByteLength += 3;
}else if((0x010000 <= charCode) && (charCode <= 0x10FFFF)){ //此分支基本用不上//0x010000 - 0x10FFFF:4字节
totalByteLength += 4;
}
}
alert(totalByteLength);
return totalByteLength;
}
javascript获取字符的字节长度
最新推荐文章于 2024-04-08 18:22:08 发布