Skip to content

Instantly share code, notes, and snippets.

  • Save ElliotFriend/0c94ff925b06ff3ca432 to your computer and use it in GitHub Desktop.
Save ElliotFriend/0c94ff925b06ff3ca432 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/elliotfriend 's solution for Bonfire: Truncate a string
// Bonfire: Truncate a string
// Author: @elliotfriend
// Challenge: http://www.freecodecamp.com/challenges/bonfire-truncate-a-string?solution=function%20truncate(str%2C%20num)%20%7B%0A%20%20%2F%2F%20Clear%20out%20that%20junk%20in%20your%20trunk%0A%20%20var%20maxLength%20%3D%20num%3B%0A%20%20if%20(num%20%3E%203)%20%7B%20maxLength%20%3D%20num%20-%203%3B%20%7D%0A%20%20if%20(num%20%3E%3D%20str.length)%20%7B%0A%20%20%20%20return%20str%3B%0A%20%20%7D%20else%20%7B%0A%20%20%20%20return%20str.slice(0%2C%20maxLength)%20%2B%20%22...%22%3B%0A%20%20%7D%0A%7D%0A%0Atruncate(%22A-tisket%20a-tasket%20A%20green%20and%20yellow%20basket%22%2C%2011)%3B%0A
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function truncate(str, num) {
// Clear out that junk in your trunk
var maxLength = num;
if (num > 3) { maxLength = num - 3; }
if (num >= str.length) {
return str;
} else {
return str.slice(0, maxLength) + "...";
}
}
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