简体   繁体   中英

Truncate text with ellipses but without cutting the last word

I truncate my title with ellipsis by limiting it to 3 lines and 150 characters, but I have my last word which is cut. I looked for a solution without finding one that suits me.

In my html:

  <span class="w-100 data-set-card-title data-set-card-title-margin">{{card.resource_title}</span>

In my css:

font-size: 20px;
    font-weight: 400;
    color: $rudi-primary-color;
    display: -webkit-box;
    margin-bottom: 5px;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    hyphens: auto;
    min-height: 1.2em;

Result:

It has long been known that working with readable, meaningful text is distracting, and distracts from focusing on the layout itself. The advantage of the Lor... (last word is Lorem)

what i would like:

It has long been known that working with readable, meaningful text is distracting, and distracts from focusing on the layout itself. The advantage of the... (so we don't cut the word in the middle).

If you have any suggestions for me i'm taker

I found a solution using a pipe, for those who will have the same problem:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'truncateText'
})
export class TruncateTextPipe implements PipeTransform {

  transform(value: string, length: number): string {
    const biggestWord = 50;
    const elipses = "...";
    if (typeof value === "undefined") return value;
    if (value.length <= length) return value;
    //.. truncate to about correct lenght
    let truncatedText = value.slice(0, length + biggestWord);
    //.. now nibble ends till correct length
    while (truncatedText.length > length - elipses.length) {
      let lastSpace = truncatedText.lastIndexOf(" ");
      if (lastSpace === -1) break;
      truncatedText = truncatedText.slice(0, lastSpace).replace(/[!,.?;:]$/, '');
    }
    return truncatedText + elipses;
  }
}

-Template:

<span class="w-100 data-set-card-title data-set-card-title-margin" *ngIf="mediaSize.isMd">{{card.resource_title **| truncateText: 80**}}</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM