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?

5 Answers 5

135

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); 
Sign up to request clarification or add additional context in comments.

5 Comments

$.trim(title) was suggested - I agree since it will handle IE<9 too
It's an edge case, but if the first word of the title is 10 or more characters, this returns "..."
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.
Good answer. I would opt for using &hellip; rather than three separate dots though, but its really a matter of preference.
Here is the single character for 3 dots:
46

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) + "..."; 

2 Comments

Perfect! Thank you so much for providing this patch.
This adds the omission( the three dots ) when the string is shorter than 10 characters >jQuery.trim("test").substring(0, 10).trim(this) + "..."; "test..."
38
 function truncateString(str, length) { return str.length > length ? str.substring(0, length - 3) + '...' : str } 

2 Comments

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...
This solution can handle strings shorter than max length, but does truncate mid-word.
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; } 

2 Comments

It actually can break words but it's just what I was searching for. Also, nice mustache.
I think it will not work for multi lines text as in paragraph.
1

with prototype and without space :

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.