Use slice and add ellipsis for truncation
const text = 'This is a very long text';
const truncated = text.length > 20
? text.slice(0, 20) + '...'
: text;
console.log(truncated); // "This is a very long..."function truncate(str, maxLength, suffix = '...') {
if (str.length <= maxLength) return str;
return str.slice(0, maxLength - suffix.length) + suffix;
}
console.log(truncate('Hello World', 8));
// Truncate at word boundary
function truncateWords(str, maxLength) {
if (str.length <= maxLength) return str;
const truncated = str.slice(0, maxLength);
const lastSpace = truncated.lastIndexOf(' ');
return lastSpace > 0
? truncated.slice(0, lastSpace) + '...'
: truncated + '...';
}
console.log(truncateWords('Hello beautiful world', 15));
// Truncate middle
function truncateMiddle(str, maxLength) {
if (str.length <= maxLength) return str;
const charsToShow = maxLength - 3;
const frontChars = Math.ceil(charsToShow / 2);
const backChars = Math.floor(charsToShow / 2);
return str.slice(0, frontChars) + '...' + str.slice(-backChars);
}function truncateHTML(html, maxLength) {
const text = html.replace(/<[^>]+>/g, '');
return truncate(text, maxLength);
}const smartTruncate = (str, max) =>
str.length > max
? str.slice(0, str.lastIndexOf(' ', max)) + '...'
: str;Avoid CSS text-overflow when you need the actual string
// DON'T DO THIS if you need the truncated value in JS
element.style.textOverflow = 'ellipsis';✓ Works in all modern browsers (ES5+)