Truncate a String - I don't understand code

Hi,

I don’t understand why I am using

return str.slice(0, (num - 3)) + '...';

in this challenge.

It is (num-3) that I don’t understand? Why am I using this?

I think I should be using (num-1) as this would truncate the string at the maximum string length (second argument).

In the example:

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

my understanding of the code is that (num-3) would mean it gets truncated at the 5th letter in the string here:

A-tisk

and not at:

A-tisket

(the 8th letter as requested in the challenge).

What am I reading wrong?

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/74.0.3729.169 Safari/537.36.

Link to the challenge:

The challenge hints are wrong and outdated, it use to ask for you to include the eplisis (…) into your second arguments count IE: hello… would be 8 rather than 5
edit:
The new one can be found here where you would use num rather than num-3

https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/index.md

1 Like