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?
Essentially, you check the length of the given string. If it's longer than a given length n , clip it to length n ( substr or slice ) and add html entity … (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With