Reputation: 120
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.
Upvotes: 3
Views: 1599
Reputation: 1
//Manish Bhardwaj
var regex = /\s+/gi;
//for count the words.
var count = (data.description).trim().replace(regex,' ').split(' ').length;
// for split all string data in array form
$scope.substr = (data.description).trim().replace(regex,' ').split(' ');
//make substring with space which is trimmed.
$scope.substr1 = $scope.substr.slice(0,20).join(' ');
$scope.substr2 = $scope.substr.slice(20,40).join(' ');
$scope.substr3 = $scope.substr.slice(40,$scope.substr.length).join(' ');
Upvotes: 0
Reputation: 330
a cleaner solution would be something like this:
<span>{{((longStringArray = longString.split(' ')) | limitTo: wordLimit = 20).join(' ')}}</span>
<span ng-if="longStringArray.length > wordLimit"> ...</span>
this even displays ' ...' at the end, to indicate that the given string was shortened.
Upvotes: 0
Reputation: 4274
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}}
Upvotes: 5