Posted By

kgriffs on 09/10/10


html String truncate fit ellipses

Versions (?)

Who likes this?

5 people have marked this snippet as a favorite


Smart String Truncate with Ellipses

 / Published in: JavaScript


This handy jQuery extension function truncates strings so they will fit in a given number of characters (e.g., when trying to fit a string into a fixed-width column). We are using it for the Gammeta control panel and thought it was handy enough to share. The smartness of this function comes in the way it tries to truncate at word boundaries. For example, a naive algorithm would turn My Super Indie Game into My Super Ind..., whereas the function shown here would output My Super... instead.

  1. (function($) {
  2. $.fit = function(str, nMaxChars) {
  3. if (str.length <= nMaxChars)
  4. return str;
  6. var xMaxFit = nMaxChars - 3;
  7. var xTruncateAt = str.lastIndexOf(' ', xMaxFit);
  8. if (xTruncateAt == -1 || xTruncateAt < nMaxChars / 2)
  9. xTruncateAt = maxFit;
  11. return str.substr(0, xTruncateAt) + "...";
  12. };
  13. })(jQuery);

Report this snippet  


RSS Icon Subscribe to comments
Posted By: BarrydeRond on October 10, 2010

This is nicer to implement:

/* String trunc */
String.prototype.trunc = function(value){ 
  return this.substr(0, value-1) + (this.length > value ? '...' : ''); 

var myString = "bla bla bla"; myString.trunc(3); /* bla... */

Posted By: kgriffs on November 18, 2010

Yes, but that algorithm doesn't take spaces into account, so it's less useful for truncating titles, sentences, etc.

Posted By: kgriffs on November 18, 2010

Note: I recently fixed a couple bugs in the algorithm. Please try out the new code and let me know if you find any problems.

You need to login to post a comment.