Created
January 6, 2011 00:09
-
-
Save tbeseda/767275 to your computer and use it in GitHub Desktop.
truncate a string to a set number of chars and add ellipses with respect for non-word characters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function fit(str, nMaxChars) { | |
| var n = nMaxChars - 1, | |
| strRX = /\s|\.|,/, | |
| tmp_str = str.slice(0, n), | |
| final_str; | |
| if (str.length <= n) return str; | |
| function getLastChar(str) { | |
| return str.slice(str.length-1, str.length); | |
| } | |
| function trimLastChar(str) { | |
| return str.slice(0, str.length - 1); | |
| } | |
| (function isLast(lstr){ | |
| var lastChar = getLastChar(lstr), | |
| short_str = trimLastChar(lstr), | |
| short_lastChar = getLastChar(short_str); | |
| if( strRX.test(lastChar) ) { | |
| final_str = ( /\W/.test(short_lastChar) ) ? trimLastChar(short_str) : short_str; | |
| final_str += "..."; | |
| } else { | |
| isLast(short_str); | |
| } | |
| })(tmp_str); | |
| return final_str; | |
| } |
Author
Badass. Adding to my snippets lib.
But it doesn't respect word breaks: http://jsfiddle.net/tbeseda/H5Hsk/1/
an easy addition: http://jsfiddle.net/wookiehangover/VTPta/2/
Author
Just one thins. Needed to check the length to see if it was already <= n
if(str.length <= n) return str;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made a shorter version :)
http://jsfiddle.net/wookiehangover/VTPta/