Truncate a string v9

Tell us what’s happening:
I need the test to return “Peter Piper…”, but it returns “Peter Piper pi…”. Any ideas how I can reduce the slice() 3 more characters?

Your code so far

function truncateString(str, num) {
  if (str.length > num){
    var a = str.slice(0, num) + '...';
    return a;
  }
  else if (str.length <= num){
    var b = str.slice(0, num);
    return b;
  }
}

truncateString("Peter Piper picked a peck of pickled peppers", 14);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/truncate-a-string

call the function with 11, not 14. Peter Piper is 11 chars, not 14. If you have to call it with 14, use num - 3 inside the function, that doesn’t seem correct though.
incidentally, the else isn’t required.

I think you need three possibility in your if ... else :
When num is lower than three,
when num is greater than the array length
and the other cases (when num is between 3 and the array length)

:slight_smile:

1 Like

I can’t pick (num)…it’s a test so the computer runs a bunch of different (str) and (num) combinations against my code.

You can’t slice form 0 to a none existent letter. I would say just remove that else if and just put return str

It will only return str if it doesn’t return a.