Created
December 14, 2014 11:51
-
-
Save davebarnwell/577336339e5e9709f136 to your computer and use it in GitHub Desktop.
truncate string on word boundary
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 truncate(str, len) { | |
| if (str.length > len) { | |
| var new_str = str.substr (0, len+1); | |
| while (new_str.length) { | |
| var ch = new_str.substr ( -1 ); | |
| new_str = new_str.substr ( 0, -1 ); | |
| if (ch == ' ') { | |
| break; | |
| } | |
| } | |
| if ( new_str === '' ) { | |
| new_str = str.substr ( 0, len ); | |
| } | |
| return new_str +'...'; | |
| } | |
| return str; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment