Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string to a certain word count

Tags:

angularjs

trim

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.

like image 742
cristina pietersen Avatar asked Dec 30 '25 04:12

cristina pietersen


1 Answers

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}}
like image 91
Reyraa Avatar answered Jan 01 '26 18:01

Reyraa