My code for Truncate a String problem is correct but not working

Tell us what’s happening:

Why doesn’t this code work? I’m testing it out in my console and all the examples that it says I’m failing are coming out correct?

Your code so far


function truncateString(str, num) {
  // Clear out that junk in your trunk
  str.slice(0, num) + '...';
  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/71.0.3578.98 Safari/537.36.

Link to the challenge:

str.slice(0, num) does not modify str. You need to make some adjustments.

Did you get it yet?

Let me try to be a bit more helpful:

First, you must return the value from str.slice(0, num) + ‘…’;

You only return the original str if num === str.length, so you will need a condition there (if…).

Hope this will help you figure it out :slight_smile:

Oh wait so am I just returning the string parameter as soon as it’s past to the function?

function truncateString(str, num) {
// so the modified string exits in this line
str.slice(0, num) + ‘…’;
//while instead of taking that modified string I’m taking the parameter unchanged?
return str;
}

so i changed it to this

function truncateString(str, num) {
return str.slice(0, num) + ‘…’;
}

this still doesn’t work, I don’t see what you mean man

Part of being a dev is playing very close attention to details.

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

It doesn’t say to truncate it to num characters and then add the ellipsis. Only add the ellipsis is the string was more than num characters.

If you look at the bottom left, it tells you exactly what failed and why:

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

Read closely.

Geo was trying to point you in the right direction when he said, “You only return the original str if num === str.length, so you will need a condition there (if…).”

Let us know if you are still stuck.

Ok I see thanks guys

So, you’ve figured it out? Great! Actually, I should have said “you only return the original str if num >= str.length”. :smiley: