Basic Algorithm Scripting: Truncate a String

Basic Algorithm Scripting: Truncate a String
0

#1

Tell us what’s happening:

what am I doing wrong? I have searched everywhere and even copied and pasted some other solutions that were online and nothing worked. It keeps telling
“truncateString(“A-tisket a-tasket A green and yellow basket”, 8) should return “A-tisket…”.
truncateString(“Peter Piper picked a peck of pickled peppers”, 11) should return “Peter Piper…”.”

Your code so far


function truncateString(str, num) {
  // Clear out that junk in your trunk
 if (str.length > num && num > 3) {
    return str.slice(0, (num - 3)) + '...';
  } else if (str.length > num && num <= 3) {
    return str.slice(0, num) + '...';
  } else {
    return str;
  }

}


truncateString("A-tisket a-tasket A green and yellow basket", 8);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/


#2

Can you explain to me why you are checking if num > 3 if the first if statement?


#3

Wouldn’t that be equal to the number of dots that we are adding “…”? I don’t know, I am confused.


#4

This challenge is straight forward:

If the length of the string (str) is longer than the specified max (num), then truncate str so that it’s length is no longer than num and then add ‘…’ to the end. Otherwise, just return str.