/ Published in: JavaScript
URL: http://gammeta.com
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.
Expand |
Embed | Plain Text
(function($) { $.fit = function(str, nMaxChars) { if (str.length <= nMaxChars) return str; var xMaxFit = nMaxChars - 3; var xTruncateAt = str.lastIndexOf(' ', xMaxFit); if (xTruncateAt == -1 || xTruncateAt < nMaxChars / 2) xTruncateAt = maxFit; return str.substr(0, xTruncateAt) + "..."; }; })(jQuery);
Comments
Subscribe to comments
You need to login to post a comment.

This is nicer to implement:
var myString = "bla bla bla"; myString.trunc(3); /* bla... */
Yes, but that algorithm doesn't take spaces into account, so it's less useful for truncating titles, sentences, etc.
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.