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?
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.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); … rather than three separate dots though, but its really a matter of preference.…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) + "..."; function truncateString(str, length) { return str.length > length ? str.substring(0, length - 3) + '...' : str } Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.
.truncated { display:inline-block; max-width:100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }