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

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

当前回答

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

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

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

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

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

其他回答

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

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

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

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

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

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

最好的函数。归功于文本省略。

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}

例子:

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"

如果使用Ext.js,可以使用Ext.util.Format.ellipsis函数。

使用任一lodash的截断

_.truncate('hi-diddly-ho there, neighborino');
// → 'hi-diddly-ho there, neighbo…'

或下划线。字符串截断。

_('Hello world').truncate(5); => 'Hello...'