Skip to content

Instantly share code, notes, and snippets.

@SerhiiLihus
Created December 2, 2015 11:35
Show Gist options
  • Save SerhiiLihus/4ca0ec68a0fe7b30a677 to your computer and use it in GitHub Desktop.
Save SerhiiLihus/4ca0ec68a0fe7b30a677 to your computer and use it in GitHub Desktop.
Truncate a string
// Bonfire: Truncate a string
// Author: @serhiilihus
// 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%20if%20(num%20%3E%3D%20str.length%20)%20%7B%0A%20%20%20%20return%20str%3B%0A%20%20%7D%20else%20if%20(%20num%20%3E%203)%20%7B%0A%20%20%20%20str%20%3D%20str.substr(0%2Cnum%20-%203)%20%2B%20%22...%22%3B%0A%20%20%7D%20else%20%7B%0A%20%20%20%20str%20%3D%20str.substr(0%2Cnum)%20%2B%20%22...%22%3B%0A%20%20%7D%0A%20%20return%20str%3B%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) {
if (num >= str.length ) {
return str;
} else if ( num > 3) {
str = str.substr(0,num - 3) + "...";
} else {
str = str.substr(0,num) + "...";
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment