有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
在我看来,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 + '…';
};
其他回答
人们希望用JavaScript而不是CSS来实现这一点是有充分理由的。
在JavaScript中截断为8个字符(包括省略号):
short = long.replace(/(.{7})..+/, "$1…");
or
short = long.replace(/(.{7})..+/, "$1…");
注意,这只需要在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获得了该代码片段。
如果你想用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;
}
这里是我的解决方案与字边界。
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.truc= function (length) {
return this.length>length ? this.substring(0, length) + '…' : this;
};
用法:
"this is long length text".trunc(10);
"1234567890".trunc(5);
输出:
这是… 12345年……