Created
December 9, 2015 22:35
-
-
Save anonymous/43c0b4181fd92a8aa852 to your computer and use it in GitHub Desktop.
http://www.freecodecamp.com/goteamtim 's solution for Bonfire: 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
| // Bonfire: Truncate a string | |
| // Author: @goteamtim | |
| // Challenge: http://www.freecodecamp.com/challenges/bonfire-truncate-a-string | |
| // Learn to Code at Free Code Camp (www.freecodecamp.com) | |
| function truncate(str, num) { | |
| var dots = ''; | |
| if(num>3){ | |
| dots = '...'; | |
| } | |
| //check that the string is longer than the number | |
| if(str.length > num){ | |
| //slice the string | |
| var slicedString = str.slice(0,num); | |
| //If the string is greater than 4 then add the dots and remove three charachters | |
| if(slicedString.length > 4){ | |
| slicedString = slicedString.slice(0,slicedString.length-3) + dots; | |
| return slicedString; | |
| }else{//return the string which is less than 4 charachters with the dots | |
| return slicedString + '...'; | |
| } | |
| } | |
| 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