【发布时间】:2011-01-09 06:12:28
【问题描述】:
我有很长的标题,想截断它们,但以一种没有单词中断的方式,我的意思是在单词之间进行切割而不是切割一个单词。
我如何使用 jquery 来做到这一点?
【问题讨论】:
标签: javascript jquery string
我有很长的标题,想截断它们,但以一种没有单词中断的方式,我的意思是在单词之间进行切割而不是切割一个单词。
我如何使用 jquery 来做到这一点?
【问题讨论】:
标签: javascript jquery string
发件人: jQuery text truncation (read more style)
试试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
你也可以使用插件:
作为字符串的扩展
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
用作
"This is your title".trimToLength(10);
【讨论】:
…,而不是三个单独的点,但这确实是一个偏好问题。
如果原始字符串没有空格,上述解决方案将不起作用。
试试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.trim(this) + "...";
【讨论】:
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
【讨论】:
不要使用 jQuery,而是使用 css 属性 text-overflow:ellipsis。它会自动截断字符串。
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
【讨论】:
有原型,没有空格:
String.prototype.trimToLength = function (trimLenght) {
return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};
【讨论】: