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

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

当前回答

有时文件名是编号的,其中索引可能在开头或结尾。所以我想从弦的中心开始缩短:

function stringTruncateFromCenter(str, maxLength) {
    const midChar = "…";      // character to insert into the center of the result
    var left, right;

    if (str.length <= maxLength) return str;

    // length of beginning part      
    left = Math.ceil(maxLength / 2);

    // start index of ending part   
    right = str.length - Math.floor(maxLength / 2) + 1;   

    return str.substr(0, left) + midChar + str.substring(right);
}

请注意,我在这里使用了UTF-8中超过1个字节的填充字符。

其他回答

我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。

var long = "hello there! Good day to ya."
// hello there! Good day to ya.

var short  = long.slice(0, 5)
// hello

也许我错过了一个例子,有人在处理空值,但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 "";
      }
  }
('long text to be truncated').replace(/(.{250})..+/, "$1…");

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

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

如果你想用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;
}

该功能还可以截断空格和文字部分。(例如:母亲变成飞蛾……)

String.prototype.truc= function (length) {
        return this.length>length ? this.substring(0, length) + '&hellip;' : this;
};

用法:

"this is long length text".trunc(10);
"1234567890".trunc(5);

输出:

这是… 12345年……