Truncate Text to a Maximum Length in JavaScript
User interfaces often need a shortened preview of longer text. A small helper can truncate a string to a maximum length and append an ellipsis when necessary. function limitText(text, limit) { if (typeof text !== 'string') return ''; if (!Number.isInteger(limit) || limit < 0) { throw new RangeError('limit must be a non-negative integer'); } if (text.length <= limit) return text; return `${text.slice(0, limit)}...`; } Examples: