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

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

当前回答

注意,这只需要在Firefox中执行。

所有其他浏览器都支持CSS解决方案(参见支持表):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

具有讽刺意味的是,我从Mozilla MDC获得了该代码片段。

其他回答

我对Kooilnc的解决方案投了赞成票。非常好的紧凑解决方案。有一个小的边缘情况,我想解决。如果有人出于某种原因输入了一个很长的字符序列,它不会被截断:

function truncate(str, n, useWordBoundary) {
    var singular, tooLong = str.length > n;
    useWordBoundary = useWordBoundary || true;

    // Edge case where someone enters a ridiculously long string.
    str = tooLong ? str.substr(0, n-1) : str;

    singular = (str.search(/\s/) === -1) ? true : false;
    if(!singular) {
      str = useWordBoundary && tooLong ? str.substr(0, str.lastIndexOf(' ')) : str;
    }

    return  tooLong ? str + '&hellip;' : str;
}
('long text to be truncated').replace(/(.{250})..+/, "$1…");

不知何故,上面的代码是不工作的某种复制粘贴或书面文本在vuejs应用程序。所以我使用lodash截断,它现在工作正常。

_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});

在我看来,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;';
    };

聪明的地方:D

//My Huge Huge String let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).` //Trim Max Length const maxValue = 50 // The barber. const TrimMyString = (string, maxLength, start = 0) => { //Note - `start` is if I want to start after some point of the string if (string.length > maxLength) { let trimmedString = string.substr(start, maxLength) return ( trimmedString.substr( start, Math.min(trimmedString.length, trimmedString.lastIndexOf(' ')) ) + ' ...' ) } return string } console.log(TrimMyString(tooHugeToHandle, maxValue))

也许我错过了一个例子,有人在处理空值,但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_ + '&hellip;' : s_;
 };

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

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