Skip to content

Instantly share code, notes, and snippets.

@ccnixon
Created February 9, 2016 20:41
Show Gist options
  • Save ccnixon/b3948dbae4eadb1b277c to your computer and use it in GitHub Desktop.
Save ccnixon/b3948dbae4eadb1b277c to your computer and use it in GitHub Desktop.
Truncate a string: Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a "..." ending.
function truncate(str, num) {
// Clear out that junk in your trunk
return num >= str.length? str: str.slice(0, num - (num <= 3 ? 0 : 3)) + '...';
}
truncate("A-tisket a-tasket A green and yellow basket", 11);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment