需要提前说明的知识点:
字符串的length属性返回的是字符的个数,不是字节的个数耨!
按字节数截取字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function strEllipsis(str, targetLen) { if (str == null) return ''; if (typeof str != "string"){ str += ""; } else { str = str.trim(); } let len = str.length, charLength = 0; for (let i = 0; i < len; i++) { if (/[^\x00-\xff]/.test(str.charAt(i))) { charLength += 2; } else { charLength += 1; } if (charLength > targetLen) { return str.substr(0, i)+'...'; } if (i == (len-1) && (charLength <= targetLen)) { return str.substr(0, i+1); }
} }
|