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

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

当前回答

这里是我的解决方案与字边界。

let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." let s_split = s.split(/\s+/); let word_count = 0; let result = ""; //1 for(let i = 0; word_count < 100; i++){ word_count += s_split[i].length+1; result += (s_split[i] + " "); } console.log(result); // 2 word_count = 0; result = s_split.reduce((x,y)=>{ word_count+=(y.length+1); if(word_count>=100) return x; else return x+" "+y;}, "").substring(1); console.log(result);

其他回答

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

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

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

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

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

修正Kooilnc的解决方案:

String.prototype.trunc = String.prototype.trunc ||
  function(n){
      return this.length>n ? this.substr(0,n-1)+'&hellip;' : this.toString();
  };

如果不需要截断string对象,则返回string值而不是string对象。

这里是我的解决方案与字边界。

let s = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." let s_split = s.split(/\s+/); let word_count = 0; let result = ""; //1 for(let i = 0; word_count < 100; i++){ word_count += s_split[i].length+1; result += (s_split[i] + " "); } console.log(result); // 2 word_count = 0; result = s_split.reduce((x,y)=>{ word_count+=(y.length+1); if(word_count>=100) return x; else return x+" "+y;}, "").substring(1); console.log(result);

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

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个字符

注意,这只需要在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获得了该代码片段。