Confused about Truncate a string problem

Hello Everyone,

I’m so confused. I don’t understand how FreeCode camp are coming up with there outputs.

truncateString(“A-tisket a-tasket A green and yellow basket”, 11) should return “A-tisket…”.

truncateString(“Peter Piper picked a peck of pickled peppers”, 14) should return “Peter Piper…”.

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

truncateString(“A-”, 1) should return “A…”.

truncateString(“Absolutely Longer”, 2) should return “Ab…”.

My question is. How do I know when to truncate the string at a particular index? It seems like there randomly choosing an index and truncating the string.

Hi,

All you have to do is count, from the beginning of the given string, the number of characters passed through the second argument (-3, to give space to the three dots). In case the given string is less than three characters long, you just place the three dots.

Make sense?

Happy coding!

Can you give me example? I’m having trouble visualizing it…

This is my code so far. I don’t think I fully understand whats really being asked of me.

function truncateString(str, num) {
    
    var maxNum = 3;
    var b = 0;
  
  if(str.length > num){
      b = num - maxNum;
     return str.slice(0 , b) + "...";
  }
  else if(num <= 3){
      b = num - maxNum;
     return str.slice(0,b);
  }
}

truncateString("A-", 1);

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Thanks Randelldawson. Any ideas or hints I could get…:slight_smile:

So, this one took me awhile as well and all of their solutions were not working. I finally broke it down and got it to pass all of the tests. I did not need to do the num - 3 part, it was throwing the code off.

function truncateString (str, num) {
// if the length of the str is greater than the num
 if (str.length > num ) {
  //  return the str ending at the num and then add ...
   return str.slice(0, num) + '...';
  }
  // else return just the str
  return str
}