Skip to content

Instantly share code, notes, and snippets.

@piqueen314
Created December 11, 2015 05:43
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 piqueen314/87dc90c9733b24a71d37 to your computer and use it in GitHub Desktop.
Save piqueen314/87dc90c9733b24a71d37 to your computer and use it in GitHub Desktop.
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a "..." ending.
// Bonfire: Truncate a string
// Author: @piqueen314
// Challenge: http://www.freecodecamp.com/challenges/bonfire-truncate-a-string
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function truncate(str, num) {
// Clear out that junk in your trunk
if(num <=3)
{
return str.slice(0,num)+"...";
}else{
if(str.length>num)
{
return str.slice(0,num-3)+"...";
}
}
return str;
}
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