Last active
June 21, 2016 14:37
-
-
Save brainyfarm/de320dcb1da176db387c2865fa41daf1 to your computer and use it in GitHub Desktop.
Olawale/FreeCodeCamp Algorithm: Truncate a String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function truncateString(str, num) { | |
//if num is less or equal to 3 | |
if (num<=3) { | |
//setting up variable word, where str is equal to num letters + ... (starting ar zero, going through num length) | |
var word = str.slice(0, num) + ('...'); | |
//returning word | |
return word; | |
//if num is longer or equal to str length | |
} else if (num >= str.length) { | |
//setting up variable fullWord where str is equal to num letters (starting at 0, going through num length) | |
var fullWord = str.slice(0, num); | |
//returning fullWord | |
return fullWord; | |
//in any other cases | |
} else { | |
// setting up variable shortWord, where str is sliced from the end to -length of str - num; removing additional 3 letters so ... can take their space | |
var shortWord = str.slice(0, -(str.length-num)-3) + ('...'); | |
//returning shortWord | |
return shortWord; | |
} | |
} | |
truncateString("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