To truncate text in a way that looks good and retains substances is surprisingly complicated. I started writing my own after being frustrated with the built-in truncate method in Hugo.
A good text truncation method has the following requirements:
- Maximizes the amount of characters to the target limit
- Minimizes breaking paragraphs, sentences, lists, and words
- Appends ellipses if the input does not fit within the target limit
- Accounts for the addition of ellipses in the target limit
- Ignores the title/heading if it’s also in the input text
As a simple example, given this input text:
> Quisque efficitur nunc sit amet lacus blandit, quis condimentum magna sodales vestibulum molestie suscipit libero, id eleifend nisl facilisis sit amet.
With a truncation limit of 140, the output should be:
> Quisque efficitur nunc sit amet lacus blandit, quis condimentum magna sodales. Vestibulum molestie suscipit libero, id eleifend nisl . . .
Links to this note
-
Line Clamp With React and Tailwindcss
Tailwind has a plugin for line clamping
@tailwindcss/line-clamp
that uses pure CSS to truncate text to the specified number of lines. What if you want to show an indicator to read the rest of the truncated text?