// 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…
Create a free account and build your private vault. Share publicly whenever you want.