truncate.js
fast, intelligent javascript text truncation
truncate.js: cut text where the layout actually breaks
truncate.js truncates text based on measured rendered height rather than character counts, with options for line limits, ellipsis, and show more buttons. The README is candid about where it fails.
Height-based cutting
The core idea is that text should be cut where the rendered layout says to cut, not at an arbitrary character count. Options include lineHeight for the line height in pixels with auto as the default, lines for the maximum line count, and ellipsis for the marker text appended at the cut point. Position can be start, middle, or end, and maxHeight caps the content at a fixed height.
Show more and show less
Two options insert HTML at the truncation point. showMore is meant for a show more button, and showLess provides the HTML used when the expand method is called. Because the decision is based on measured height, the library works across different font metrics instead of guessing from string length.
Where it gives up
The README lists the cases that break it, mostly because text height is hard to compute there. Truncating a node with a floating element, a node whose descendants carry padding, or a node with text of mixed line heights all make the list. It is presented as an honest boundary rather than a claim of universal coverage.
Building and shipping
Development is described as simple: hack on the code, make sure lint and tests pass, and submit a pull request. That needs node and npm installed. The stack is Mocha as the test runner in BDD style, Chai as the assertion library in assert style, and Gulp as the builder.
Editorial conclusion
The library measures height instead of counting characters, which is the right call for real layouts and the source of its caveats. The README names three cases where it gives up.
Community notes