app/shared/pipes/truncate-text.pipe.ts
Name | truncatetext |
transform |
transform(value: string, length: number)
|
Defined in app/shared/pipes/truncate-text.pipe.ts:10
|
Returns :
string
|
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 (!value || value.length <= length) {
return value;
}
let truncatedText = value.slice(0, length + biggestWord);
while (truncatedText.length > length - elipses.length) {
let lastSpace = truncatedText.lastIndexOf(' ');
if (lastSpace === -1) {
break;
}
truncatedText = truncatedText.slice(0, lastSpace).replace(/[!,.?;:]$/, '');
}
return truncatedText + elipses;
}
}