js 获取字符串的字节数

function getLength(str) {
var totalLength = 0;
var charCode;
for (var i = 0; i < str.length; i++) {
charCode = str.charCodeAt(i);
if (charCode < 0x007f) {
totalLength++;
} else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
totalLength += 2;
} else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
totalLength += 3;
} else{
totalLength += 4;
}
}
return totalLength;
}

var oneName = “sodasjd”;
alert(oneName);
原文地址:https://www.cnblogs.com/aifengguo/p/7028795.html