如何在jQuery中截断字符串? [英] How Can I Truncate A String In jQuery?
本文介绍了如何在jQuery中截断字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很长的头衔并希望截断它们但是在某种程度上没有任何文字突破,我的意思是切割发生在不切词的单词之间。
I have long titles and want truncate them but in a way that no words break, I mean the cutting happen between words not cutting a word.
我怎么能使用jquery吗?
How can I do it using jquery?
推荐答案
试试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
- 在此测试
- Tested here
- jQuery Expander Plugin
您还可以使用插件:
作为String的扩展
As a extension of String
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);
这篇关于如何在jQuery中截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文