修剪字符串一定字数 [英] trim string to a certain word count

查看:136
本文介绍了修剪字符串一定字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个描述我的模板

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

我要修剪这说明一定的字数,如先20个字。我见过很多的过滤器,但他们修剪到一定的字符。这导致最后一个字在多数情况下破裂。
结果
在此先感谢

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.
thanks in advance

推荐答案

您需要的描述字符串分割成单词,使用空格,再算吧:

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

这篇关于修剪字符串一定字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆