hd.*_*hd. 61 javascript string jquery
我有很长的头衔,想要截断它们但是在某种程度上没有任何文字突破,我的意思是切割发生在不切词的单词之间.
我怎么能用jquery呢?
Nav*_*eed 123
试试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
Run Code Online (Sandbox Code Playgroud)
你也可以使用插件:
作为String的扩展
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Run Code Online (Sandbox Code Playgroud)
用于
"This is your title".trimToLength(10);
Run Code Online (Sandbox Code Playgroud)
小智 40
如果原始字符串没有空格,则上述解决方案将不起作用.
试试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.trim(this) + "...";
Run Code Online (Sandbox Code Playgroud)
Kea*_*ang 36
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
Run Code Online (Sandbox Code Playgroud)
而不是使用jQuery,使用css属性text-overflow:ellipsis.它会自动截断字符串.
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
Run Code Online (Sandbox Code Playgroud)