Truncate String with Ellipsis
Truncate String with Ellipsis is a reusable JavaScript snippet. Truncates a string to a specified length, adding an ellipsis (or custom suffix) at the end. The full implementation: function truncate(str, maxLength = 50, suffix = '...') { if (str.length 0 ? truncated.slice(0, lastSpace) : truncated) + suffix } // Usage const longText = 'The quick brown fox jumps over the lazy dog' truncate(longText, 20) // "The quick brown..." truncateWord(longText, 20) // "The quick brown..." This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.