// Created on savesnippets.com · https://savesnippets.com/CoIaUbKF1X86X4 export function truncateWords(text: string, max: number, ellipsis = '…'): string { const t = text.trim(); if (t.length <= max) return t; const budget = max - ellipsis.length; if (budget <= 0) return ellipsis.slice(0, max); let cut = t.slice(0, budget); const lastSpace = cut.lastIndexOf(' '); if (lastSpace > budget * 0.5) cut = cut.slice(0, lastSpace); return cut.replace(/[\s,.;:]+$/, '') + ellipsis; } truncateWords('The quick brown fox jumps over the lazy dog', 20); // 'The quick brown fox…'