I'm working on a project for freecodecamp.
Rules of the project:
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 inserting the three dots to the end will add to the string length.
However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
My test strings include:
truncateString("A-tisket a-tasket A green and yellow basket", 11)should return "A-tisket...".
truncateString("Peter Piper picked a peck of pickled peppers", 14)should return "Peter Piper...".
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)should return "A-tisket a-tasket A green and yellow basket".
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)should return "A-tisket a-tasket A green and yellow basket".
truncateString("A-", 1)should return "A...".
truncateString("Absolutely Longer", 2)should return "Ab...".
Now I've gotten most of this figured out using a ternary operator, so it's fairly simple, except the last two ('A-', 1) and ('Absolutely Longer', 2), my question being, how can I accomplish the truncating successfully and return the expected output of the last two strings?
Source:
function truncateString(str, num) {
return str.length > num ? str.slice(0, num - 3) + '...' : str;
}
num - 3on a string ("A-") of length 2 . Why are you doingnum-3? What is the purpose of yourtruncateStringsupposed to be?truncateStringis actually supposed to do. Instead of having us guess the rules from the input and expected outputs....if the string is longer than the requestednum. But they've neglected the edge case of the string being shorter than3. Or num being less than 3.num - 3every string.if/elsestatement. IF string length is less than 3, just append the...after truncation, ELSE cut off three more characters then append the...after truncation. Something like that