JavaScript
String Truncation
Truncate a string and append an ellipsis.
By EZ4Code Team
stringtruncate
Code
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);
}Explanation
Supports truncating strings by character count and byte count.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.