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
  • 69,365
  • 67
  • 217
  • 352
hd.
  • 16,676
  • 43
  • 110
  • 160

5 Answers5

133

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
  • 40,370
  • 32
  • 94
  • 130
  • 1
    $.trim(title) was suggested - I agree since it will handle IE<9 too – mplungjan Dec 15 '11 at 10:36
  • 3
    It's an edge case, but if the first word of the title is 10 or more characters, this returns "..." – Jonathan S. May 31 '13 at 21:31
  • Doesn't this fail if the it cuts right at the end of the word? ie: 'Test test sentence'.trimToLength(9) will cut out the second test, even though it's perfectly valid. – Johnny Jun 04 '14 at 01:41
  • Good answer. I would opt for using `…` rather than three separate dots though, but its really a matter of preference. – Robin Keskisarkka Nov 08 '17 at 16:08
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,280
  • 10
  • 33
  • 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... – Teak 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,562
  • 3
  • 24
  • 38
1

with prototype and without space :

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