Trim string to a certain number of words

I have a description in the template

<p>{{data.description}}</p>

      

I want to truncate this description to a specific word number, for example, to the first 20 words. I've seen a lot of filters, but they get cut off to specific characters. This results in the last word being interrupted in most cases.

+3


source to share


3 answers


You need to split the description line into words using spaces and then read:

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;
  };
});

      




I first check if the parameter is a number, then I check if this description is longer than what we need to trim, and then I trim the rest. and in the view:

{{data.description | words:250}}

      

+5


source


a cleaner solution would look something like this:

<span>{{((longStringArray = longString.split(' ')) | limitTo: wordLimit = 20).join(' ')}}</span>
<span ng-if="longStringArray.length > wordLimit"> ...</span>

      



it even displays "..." at the end to indicate that the given line has been truncated.

0


source


//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(' ');

      

0


source







All Articles