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:

  1. output valid HTML
  2. scale well performance wise
  3. 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?

  • How much leeway is there in the size of the truncated content? For (a worst-case) example, if the content were a single <p>, should the entire block be returned, no matter the value of closestToIndex?
    – outis
    May 23, 2015 at 22:07
  • no no. closestIndexOf checks to find break point between two margins and selects the one closest to selected index. If none are found between margins, index equals provided one. So it would break in the middle of paragraph. May 24, 2015 at 0:53
  • The requirements still seem under-specified. By "margins", do you mean a closing block tag (what could be termed the "left margin") and an opening block tag ("right margin")?
    – outis
    May 24, 2015 at 3:16
  • @outis: I haven't explained myself too clearly, have I? :) Sorry. This should work like: closestToIndex is i.e. character index 500. Algorithm will then go back from 500 and forwards from it. If it finds an end of block content (tags should not count as they're invisible) within ie. 100 characters (back and forth) it will then truncate content to the closest index to 500. It will truncate at that point that has a smaller delta from index 500. If it can't find the end of blocked content within this range it will simply truncate to closest word space to index 500. I hope this clears it. May 25, 2015 at 18:26


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.