Confused about Truncate a string problem

Confused about Truncate a string problem
0.0 0

#1

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.


#2

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!


#3

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


#4

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);

#5

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.


#6

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