获取字符串字节长度跟截取字符串字节长度

时间:2021-06-27 22:29:57
//获取字符串的字节长度
function getStringByteLength(str){
var realLength = 0;
for (var i = 0; i < str.length; i++)
{
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128)
realLength += 1;
else
realLength += 2;
}
return realLength;
}
//按字节截取字符串长度
function cutOutStringByteLength(str,long) {
var seeString = [];
var countByteLength = 0;
for(var i=0;i<str.length;i++){
var charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128){
countByteLength += 1;
}else{
countByteLength += 2;
}
if (countByteLength <= long){
seeString.push(str[i]);
}
}
return seeString.join("");
}