Code
javascript
function truncate(str, len = 20, suffix = "...") {
if (str.length <= len) return str;
return str.slice(0, len) + suffix;
}
// Truncate by bytes (Chinese chars take 2 bytes)
function truncateByBytes(str, bytes) {
let count = 0, i = 0;
for (; i < str.length; i++) {
count += str.charCodeAt(i) > 255 ? 2 : 1;
if (count > bytes) break;
}
return str.slice(0, i);
}