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:
console.log(limitText('Hello, world! This is a test.', 10));
// Hello, wor...
console.log(limitText('Short text.', 20));
// Short text.
Words vs. Characters
Character-based truncation can cut a word in the middle. If the UI should truncate at a word boundary, trim the sliced text back to the last space:
function limitWords(text, limit) {
if (text.length <= limit) return text;
const sliced = text.slice(0, limit);
const boundary = sliced.lastIndexOf(' ');
const result = boundary > 0 ? sliced.slice(0, boundary) : sliced;
return `${result}...`;
}Unicode Considerations
String.length and slice() operate on UTF-16 code units, so some emoji and combined Unicode characters can be split unexpectedly. For user-visible international text where grapheme boundaries matter, use Intl.Segmenter or another grapheme-aware approach.
Conclusion
A simple slice() helper is enough for many previews and card descriptions. Decide whether your UI needs character, word, or grapheme-aware truncation, then validate the input and limit explicitly.