truncate-markup-string
v1.0.2
Published
Truncates a string to a charLimit, ignoring specified markup tags, with an optional "pretty" ellipsis ending.
Downloads
49
Maintainers
Readme
truncate-markup-string
Truncates a string given a charLimit param. Provides following features:
- If truncation is necessary, ends with ellipsis (...) which is counted in the charLimit.
- Does not count chars inside supplied openTag and closeTag markup params.
- Does not break the last word.
- Does not break in the middle of an openTag and closeTag. This is especially useful when wanting to not break in the middle of a bolded statement.
- Based on boolean param prettyEllipsis, will remove punctuation at the end of the truncated text. This avoids weird endings like "?..."
Usage
import truncate from 'truncate-markup-string';
const fullString = 'This is <b class="highlight">super</b> cool? Gotta love truncation!';
const charLimit = 30;
const openTag = '<b class="highlight">';
const closeTag = '</b>';
const prettyEllipsis = true;
const result = truncate(fullString, charLimit, openTag, closeTag, prettyEllipsis);
The above code will result in the truncated string: This is <b class="highlight">super</b> cool...
.
Notice how the char limit ignored the supplied HTML tags, and the prettyEllipsis removes the question mark at the end.
Future options
Although version 1.0.2 is published and works great, there's still a lot of options and improvements that will be added to this in the future. Currently, this supports a very specific case of ignoring only one set of HTML markup tags, like bold tags. However, future support for multiple tags, a custom ellipsis, and truncation on words instead of chars will come soon.