I have HTML content in my DB and I would like to present a list of these individual items but truncate each of them so they're not fully displayed. I would like to keep truncated items human-meaningful, so I don't want to just cut content at some specific character index. As my content is HTML that specific index may be in the middle of an HTML tag for what it's worth.
I would like to truncate at specific meaningful breakpoints like end of block elements. Be it paragraphs, block quotes, code blocks, lists, list items etc. This gives the reader the possibility to get some semantically complete excerpt of the whole content.
My implementation should therefore be called like:
string truncateNear(string HTMLContent, int closestToIndex);
I would be able to provide some proximity index where function should be searching for closest HTML block end and return that content.
How would you go about truncating HTML content in such parsable way that would:
- output valid HTML
- scale well performance wise
- maybe allow searching for the first image in content and placing it right after text in trimmed content
Would it be better to transform HTML to some other format first and then manipulate that instead if it was that faster and easier to manipulate?