有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:

if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}

当前回答

也许我错过了一个例子,有人在处理空值,但3 TOP答案不适合我,当我有空值(当然,我意识到错误处理是和百万其他事情不是回答这个问题的人的责任,但由于我已经使用了一个现有的函数以及一个优秀的截断省略答案,我想我将为其他人提供它。

如。

javascript:

news.comments

使用截断函数

news.comments.trunc(20, true);

然而,在news.comments为空时,这将“中断”

最后

checkNull(news.comments).trunc(20, true) 

trunc函数由KooiInc提供

String.prototype.trunc =
 function (n, useWordBoundary) {
     console.log(this);
     var isTooLong = this.length > n,
         s_ = isTooLong ? this.substr(0, n - 1) : this;
     s_ = (useWordBoundary && isTooLong) ? s_.substr(0, s_.lastIndexOf(' ')) : s_;
     return isTooLong ? s_ + '…' : s_;
 };

我简单的空检查器(检查文字“空”的东西 (这捕获未定义,"",null, "null",等等。)

  function checkNull(val) {
      if (val) {
          if (val === "null") {
              return "";
          } else {
              return val;
          }
      } else {
          return "";
      }
  }

其他回答

大多数现代Javascript框架(JQuery, Prototype等)都有一个附加在String上的实用函数来处理这个问题。

下面是Prototype中的一个例子:

'Some random text'.truncate(10);
// -> 'Some ra...'

这似乎是您希望其他人处理/维护的功能之一。我会让框架来处理它,而不是编写更多的代码。

以下是我的解决方案,与其他建议相比有一些改进:

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

It:

在25之后的第一个空格上截断 字符 扩展JavaScript字符串对象, 因此它可以用于(并链接到) 任何字符串。 如果截断将修剪字符串 结果在一个尾随空间中; 是否添加unicode hellip实体 (省略号)如果截断的字符串长于25个字符

在我看来,C_harm的答案是最好的。请注意,如果你想使用

"My string".truncate(n)

您将不得不使用regexp对象构造函数而不是文字。此外,在转换\S时还必须转义它。

String.prototype.truncate =
    function(n){
        var p  = new RegExp("^.{0," + n + "}[\\S]*", 'g');
        var re = this.match(p);
        var l  = re[0].length;
        var re = re[0].replace(/\s$/,'');

        if (l < this.length) return re + '&hellip;';
    };

如果你想用css而不是JavaScript;

.textShortDesc { /*Here we have determined the max number of lines.*/
    display: block; /* or inline-block */
    -o-text-overflow: ellipsis; /* Opera < 11*/
    text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
    word-wrap: break-word;
    overflow: hidden;
    max-height: 2em; /*max-height/line-height=rowCount */
    line-height: 1em;
}

所有现代浏览器现在都支持一个简单的CSS解决方案,当一行文本超过可用宽度时自动添加省略号:

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

(请注意,这需要以某种方式限制元素的宽度,以便产生任何效果。)

基于https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/。

应该注意的是,这种方法并不基于字符的数量进行限制。如果需要允许多行文本,它也不能工作。