JavaScript

Truncate String

by @admin
12h ago
Apr 28, 2026
Public
Truncates a string to a maximum character length and appends an ellipsis (or custom suffix). The smart version breaks at the last word boundary to avoid cutting in the middle of a word, making truncated text look natural in card previews, notifications, and list views.
JavaScript
// Simple — cuts at exact length
const truncate = (str, max, suffix = '…') =>
  str.length <= max ? str : str.slice(0, max) + suffix;

// Word-aware — doesn't cut mid-word
const truncateWords = (str, max, suffix = '…') => {
  if (str.length <= max) return str;
  return str.slice(0, str.lastIndexOf(' ', max)) + suffix;
};

// Usage
const text = 'The quick brown fox jumps over the lazy dog';
console.log(truncate(text, 20));       // The quick brown fox…
console.log(truncateWords(text, 20));  // The quick brown…
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.