spiky
spiky

Reputation: 19

Truncate the text with ellipsis but preserving the last word

My use case: I want to display a text, limiting it to the maximum number of lines to two and truncating it with ellipsis only when it doesnt fit in the two lines, but I want to preserve the last word. I have to do this with multiple paras in the page.

eg:

Lorem asa ipsum dolor sit amet, consectetur adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat te... volutpat.

Algorithm I was thinking of:

<div class="outter">
        <div class="message" title="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.">
            <div class="firstLine"></div>
            <div class="secondLine" style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;"></div><div class="lastWord"></div>
        </div>
     </div>
  1. Get the outter div length in pixel using obj.offsetWidth;
  2. Fetch the message from message div.
  3. Find the length of string, and multiply with with approx 8 (one letter is approx 5 to 8 pixel )and compare it with outter the element width.
  4. If the length of string is greater than the twice the length of outter div, then spilt the string (this is tricky as we would want to split based on space), put the first half in firstLine div and second half in secondLine div and last word in lastWord div. (This part won't work perfectly as we don't know the exact pixel length of string )*
  5. But if string length is slightly lesser than twice the length of outter div, then the presentation will look ugly, as the second half + lastWord can either fit the secondLine div or requires both divs secondLine and lastWord div

Point me if there is any other way.

Upvotes: 0

Views: 1032

Answers (1)

user14084093
user14084093

Reputation:

Use .length to get the length of the string and a substring at that length and put an ellipsis there.

Check this if it works. Thanks!

Upvotes: 1

Related Questions