根据字符的Unicode编码
/**
* @description 对超出指定字节长度的字符截取超出部分改为 '...',如果未超出,返回原字符串
* @param str {string} 输入的字符串
* @param byteLength {number} 限制字节长度
* @return {string} 处理后的字符串
*/
public calculateByteLength(str: string, byteLength: number): string {
let len = 0 // 字节长度
let newStr = '' // 输出的字符串
for (let i = 0; i < str.length; i++) {
// 返回在字符串中i位置的字符的 Unicode 编码
let c = str.charCodeAt(i)
// 根据编码判断, 英文字符数字len+1, 中文汉字符号len+2
;(c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)
? len++
: (len += 2)
len > byteLength ? '' : (newStr += str[i])
}
return len > byteLength ? newStr + '...' : str
}