Back to Home
Strings

How to Truncate Strings

Use slice and add ellipsis for truncation

Quick Answer (2024 ES6+ Way)

javascript
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..."

Live Example

javascript
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);
}

Common Variations

HTML Truncate
javascript
function truncateHTML(html, maxLength) {
  const text = html.replace(/<[^>]+>/g, '');
  return truncate(text, maxLength);
}
Smart Truncate
javascript
const smartTruncate = (str, max) =>
  str.length > max 
    ? str.slice(0, str.lastIndexOf(' ', max)) + '...'
    : str;

❌ Don't Do This (Outdated Way)

Avoid CSS text-overflow when you need the actual string

javascript
// DON'T DO THIS if you need the truncated value in JS
element.style.textOverflow = 'ellipsis';

Browser Support

Works in all modern browsers (ES5+)

#strings#truncate#ellipsis