Igor Shvets
Igor Shvets

Reputation: 547

How to add a ... when cutting text only if its length is equal to the number of letters?

When I cut the text, I want to add "..." if its length is exactly 14 letters, if less, then cut without adding "...". How to implement ?

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

@Pipe({
    name: 'truncate'
})

export class TruncatePipe implements PipeTransform {
    transform(value: string, limit = 14, completeWords = false, ellipsis = '...') {
        if (completeWords) {
            limit = value.substr(0, limit).lastIndexOf(' ');
        }
            return `${value.substr(0, limit)}${ellipsis}`;
    }
}
<p>{{pic.title | truncate}}</p>

Upvotes: 0

Views: 71

Answers (1)

Y_Moshe
Y_Moshe

Reputation: 432

    transform(value: string, limit = 14, completeWords = false, ellipsis = '...') {
    if (completeWords === true && value.length > limit) {
       return value.substring(0, limit).concat(ellipsis);
    }
    return value; // basiclly do nothing.
}

then

<p>{{pic.title | truncate:'15':true}}</p>

Upvotes: 3

Related Questions