Skip to content

Instantly share code, notes, and snippets.

@joePichardo
Created December 10, 2015 04:28
Show Gist options
  • Save joePichardo/024b7ab1ced4b3aa723b to your computer and use it in GitHub Desktop.
Save joePichardo/024b7ab1ced4b3aa723b 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. Note that the three dots at the end add to the string length. If the num is less than or equal to 3, then the length of the three dots is not added to the string length.
// Bonfire: Truncate a string
// Author: @joepichardo
// 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
var truncString = "";
//first check string length and target num
//if num is larger return string
//if num is less than or equal to 3
//else add three leading dots and
//subtract three from num to compensate for the dots length
if(num >= str.length){
return str;
}else if(num <= 3){
truncString = str.slice(0, num);
return truncString + "...";
}else{
truncString = str.slice(0, num-3);
return truncString + "...";
}
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