69

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?

kamaci
  • 72,915
  • 69
  • 228
  • 366
hd.
  • 17,596
  • 46
  • 115
  • 165

5 Answers5

134

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);
Naveed
  • 41,517
  • 32
  • 98
  • 131
45

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) + "...";
38
  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }
Keating
  • 3,380
  • 10
  • 34
  • 42
  • 5
    The only answer that doesn't add the dots if the string is shorter then the max length. And includes the dots in the calculation... – Max Mar 04 '14 at 02:06
  • This solution can handle strings shorter than max length, but does truncate mid-word. – iamfrancisyo Jun 05 '15 at 19:33
12

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; 
           }
Ramiz Raja
  • 5,942
  • 3
  • 27
  • 39
1

with prototype and without space :

 String.prototype.trimToLength = function (trimLenght) {
    return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};