Skip to content

Truncate markup based on char length

I have markup that is passed via a data base. I need to display this markup in a valid way, but truncated. I’ve done this in the past by using sub string.

 let string = 'this is a string of text';
 string.substr(0, 165);`

But I cannot do this with markup, as it wil result in invalid markup being output as the end tags will be removed.
Example:

<h2>Titile</h2>
<p>Some long paragraph</p>
<p>Another long paragraph</p>
<p>Another long paragraph</p>
<p>Another long paragraph</p>
<ul>
    <li>list item</li>
    <li>list item</li>
    <li>list item</li>
    <li>list item</li>
</ul>
... more markup

Expected formatted output:

Title
Some long paragraph
Another long...

Can anyone think of a way of truncating the content using js or css without it resulting in broken html? Thanks.

Answer

I would suggest using the line-clamp rule in CSS. If you require IE support, then a JS solution would be required.

.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
  overflow: hidden;
}

Output:

Titile
Some long paragraph

Another long paragraph...

Demo: https://jsfiddle.net/gprLx8k9/