Truncate a String Passes all test except .length one

Tell us what’s happening:

My code passes all test except the third one:

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”.

and I don’t understand why it would fail the above and pass the fourth one:

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”.

since both look nearly identical except the + 2.

Your code so far


function truncateString(str, num) {
  let strLength = str.length;
  if(strLength < num) return str;
  // if(strLength == strLength) return str; If I uncomment this then it passes the third and fourth condition but fail everything else
  if(strLength > num) {
    let cutStr = str.slice(0, num)
    return cutStr + "...";
  }
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36.

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

You have handled the case of strLength < num and strLength > num. What should you do if strLength is equal to num?

Hint: You do do not need another if statement. You can modify one of your existing if statements.

1 Like

function truncateString(str, num) {
let strLength = str.length;
if(strLength <= num) return str;
if(strLength > num) {
let cutStr = str.slice(0, num)
return cutStr + “…”;
}
}

truncateString(“Peter Piper picked a peck of pickled peppers”, 11);

Got it! Thanks for the hint!

Now, do you really need that extra if statement or can you do something else?

function truncateString(str, num) {
let strLength = str.length;
if(strLength <= num) {
return str;
} else {
let cutStr = str.slice(0, num);
return cutStr + “…”;
}
}

:grin: It’s so exciting when it works. Thanks, Randell!

Can you also explain why in my original code it passes the 4th test but not the 3rd? I don’t understand the role of + 2 and how it affects the testing condition. Is it because < matches .length + 2 and I needed the <= to just match .length?

Yes, you understand it correctly.

1 Like