Skip to content

Instantly share code, notes, and snippets.

@davebarnwell
Created December 14, 2014 11:51
Show Gist options
  • Select an option

  • Save davebarnwell/577336339e5e9709f136 to your computer and use it in GitHub Desktop.

Select an option

Save davebarnwell/577336339e5e9709f136 to your computer and use it in GitHub Desktop.
truncate string on word boundary
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