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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just one thins. Needed to check the length to see if it was already <= n
if(str.length <= n) return str;http://jsfiddle.net/tbeseda/VTPta/3/