有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
有没有人有一个更复杂的解决方案/库,用JavaScript截断字符串,并在末尾放一个省略号,比明显的一个:
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
当前回答
我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。
var long = "hello there! Good day to ya."
// hello there! Good day to ya.
var short = long.slice(0, 5)
// hello
其他回答
使用以下代码
function trancateTitle (title) {
var length = 10;
if (title.length > length) {
title = title.substring(0, length)+'...';
}
return title;
}
注意,这只需要在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获得了该代码片段。
在我看来,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 + '…';
};
我喜欢使用.slice(),第一个参数是开始索引,第二个是结束索引。介于两者之间的都是你能得到的。
var long = "hello there! Good day to ya."
// hello there! Good day to ya.
var short = long.slice(0, 5)
// hello
以下是我的解决方案,与其他建议相比有一些改进:
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 + "…";
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…"
It:
在25之后的第一个空格上截断 字符 扩展JavaScript字符串对象, 因此它可以用于(并链接到) 任何字符串。 如果截断将修剪字符串 结果在一个尾随空间中; 是否添加unicode hellip实体 (省略号)如果截断的字符串长于25个字符