I have a description in my template
<p>{{data.description}}</p>
I want to trim this description to certain word number, like to first 20 words. I have seen many filters but they trim to a certain characters. This causes the last word to break in most cases.
You need to split the description string into words, using spaces, then count it:
app.filter('words', function () {
return function (input, words) {
if (isNaN(words)) {
return input;
}
if (words <= 0) {
return '';
}
if (input) {
var inputWords = input.split(/\s+/);
if (inputWords.length > words) {
input = inputWords.slice(0, words).join(' ') + '\u2026';
}
}
return input;
};
});
First I check if the parameter is a number, then I'm checking if the description is longer than what we what to trim at, and then I trim the rest.
and in the view:
{{data.description | words:250}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With