Created
May 24, 2018 06:20
-
-
Save Walgermo/5b75bbc026cdaa4dd84cfa0876173fd5 to your computer and use it in GitHub Desktop.
Angular 2+ truncate text pipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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