Skip to content

Instantly share code, notes, and snippets.

@jhuston
Created January 27, 2012 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhuston/1691425 to your computer and use it in GitHub Desktop.
Save jhuston/1691425 to your computer and use it in GitHub Desktop.
truncate a word at a word break. optimized for naturally occurring word breaks. with optional length argument.
truncateAtWord = function(str){
var tail = "...",
len = arguments[1] || 10;
if(str.length <= len){
return str;
}
if(str.charAt(len) === " "){
return str.slice(0,len)+tail;
}
return str.slice(0,len).split(" ").slice(0,-1).join(" ")+tail;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment