Javascript 如何在 jQuery 中截断字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4637942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I Truncate A String In jQuery?
提问by hd.
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.
我有很长的标题,想截断它们,但以一种不中断单词的方式,我的意思是切割发生在单词之间而不是切割单词之间。
How can I do it using jquery?
我如何使用 jquery 做到这一点?
回答by Naveed
From:jQuery text truncation (read more style)
Try this:
尝试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.split(" ").slice(0, -1).join(" ") + "...";
And you can also use a plugin:
您还可以使用插件:
As a extension of String
作为 String 的扩展
String.prototype.trimToLength = function(m) {
return (this.length > m)
? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
: this;
};
Use as
用于
"This is your title".trimToLength(10);
回答by Vladimir Krivchenko
The solution above won't work if the original string has no spaces.
如果原始字符串没有空格,则上述解决方案将不起作用。
Try this:
尝试这个:
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
.trim(this) + "...";
回答by Hyman Ma
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
回答by Ramiz Raja
Instead of using jQuery, use css property text-overflow:ellipsis
. It will automatically truncate the string.
不要使用 jQuery,而是使用 css property text-overflow:ellipsis
。它会自动截断字符串。
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
回答by Amine Barigo
with prototype and without space :
有原型,没有空间:
String.prototype.trimToLength = function (trimLenght) {
return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};