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.

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

Expected formatted output:

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.


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;


Some long paragraph

Another long paragraph...