Skip to content

Instantly share code, notes, and snippets.

@Walgermo
Created May 24, 2018 06:20
Show Gist options
  • Save Walgermo/5b75bbc026cdaa4dd84cfa0876173fd5 to your computer and use it in GitHub Desktop.
Save Walgermo/5b75bbc026cdaa4dd84cfa0876173fd5 to your computer and use it in GitHub Desktop.
Angular 2+ truncate text pipe
import { Pipe, PipeTransform } from '@angular/core';
/*
* Truncates an text with defined cut off length
* Takes an input parameter string.
* Usage:
* string | truncatetext: 100
* Example:
* <p>{{ string | truncatetext: 100 }}></p>
*/
@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) {
const lastSpace = truncatedText.lastIndexOf(' ');
if (lastSpace === -1) { break; }
truncatedText = truncatedText.slice(0, lastSpace).replace(/[!,.?;:]$/, '');
}
return truncatedText + elipses;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment