Skip to content

Instantly share code, notes, and snippets.

@raspo
Created April 29, 2012 17:09
Show Gist options
  • Save raspo/2551988 to your computer and use it in GitHub Desktop.
Save raspo/2551988 to your computer and use it in GitHub Desktop.
Shorten a string and optionally truncate at the last word boundary
function truncateString( string, num, useWordBoundary ){
var isLong = string.length > num,
newString = string.replace( /(^\s)|(\s$)/gi, '' ),
isOneWord = newString.match(/\s/gi) === null;
newString = isLong ? newString.substr(0,num-1) : newString;
newString = ( useWordBoundary && isLong && !isOneWord ) ? newString.substr(0,newString.lastIndexOf(' ')) : newString;
return isLong ? newString +' ...' : newString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment