Trim string to a certain word count

↘锁芯ラ 提交于 2019-12-10 21:28:03

问题


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.


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/27017147/trim-string-to-a-certain-word-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!