Truncate a String (last test cases)

Truncate a String (last test cases)
0

#1

Tell us what’s happening:

Hey everyone :slight_smile: Hope you’re all well and happy.

My code is working for all but two test cases:

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

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

As you can see, my code works for the forms where num is given as a number.

Can anyone please explain how I can modify my code to catch these last two tests?

Thanks in advance!

Your code so far


function truncateString(str, num) {
  if (str.length > num){
    str = str.slice(0, num);
    return str + "...";
  }
}

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

Your browser information:

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

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


#3

num is always passed into your function as a number in all test cases. The length of a string is a number.

The reason your solution fails, is because in the two test cases you mention above, the string’s length is not greater than num. You are currently only returning a value when this expression evaluates to true.

What do you think you should be returning if the string’s length is less than or equal to num? Once you figure that out, then make sure to return that value, because right now your current solution returns the value undefined in that situation.


#4

Hey Randell, thank you for your help!

Problem solved :slight_smile: