Truncate a String Malfunction

I’m kind of new to programming but I’ve tried everything i could think of to fix this code. I took the code exactly from the hint page that claims to be the solution and it still doesn’t work. Could someone tell me if it is my code or the programming of freecodecamp?
Thanks

Your code so far


function truncateString(str, num) {
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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

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

The solution is for the old version of this challenge, if i recall you had to make sure length of the truncated string included the extra 3 for the ‘…’ (hence the (num - 3) part).
The hint page hasn’t been updated to match this change.

This code can be easily amended to achieve the answer. If you remove the middle else if check, then only the first if check needs to be changed a bit.

Hope that helps a bit

I still cant figure it out. This one has me stumped.

Also if you look at the two first requirements to pass this algorithm, the num is greater than the string in both cases, and its stating that the return statement should be the beginning part of the string + “…”.

If you look at the two first requirements to pass this algorithm, the num is greater than the string in both cases, and its stating that the return statement should be the beginning part of the string + “…”. Doesnt my code cover this? Is the actual programming of this algorithm challenge off?

Your code so far


function truncateString(str, num) {
 if (str.length <= num){
   return str;
 }
else {
  return str.slice(0, num > 3? num - 3 : num) + '...';
}
}

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

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

If you console log the output of your code for the truncateString("A-tisket a-tasket A green and yellow basket", 8) case, it outputs “A-tis…”, while the challenge is looking for “A-tisket…”

Basically, the solution is correct as long as you get rid of the num > 3? num - 3 : part of

else {
  return str.slice(0, num > 3? num - 3 : num) + '...';
}

Hope this helps :slight_smile: