How can I create a preview of a blog post stored in HTML? In other words, how can I "cut" HTML, making sure the tags close properly? Currently, I'm rendering the whole thing on the frontend (with react's dangerouslySetInnerHTML
) then setting overflow: hidden
and height: 150px
. I would much prefer a way where I could cut the HTML directly. This way I don't need to send the entire stream of HTML to the frontend; if I had 10 blog post previews, that would be a lot of HTML sent that the visitor would not even see.
If I had the HTML (say this was the entire blog post)
<body>
<h1>Test</h1>
<p>This is a long string of text that I may want to cut.. blah blah blah foo bar bar foo bar bar</p>
</body>
Trying to slice it (to make a preview) wouldn't work because the tags would become unmatched:
<body>
<h1>Test</h1>
<p>This is a long string of text <!-- Oops! unclosed tags -->
Really what I want is this:
<body>
<h1>Test</h1>
<p>This is a long string of text</p>
</body>
I'm using next.js, so any node.js solution should work fine. Is there a way I can do this (e.g. a library on the next.js server-side)? Or will I just have to parse the HTML myself (server-side) and then fix the unclosed tags?