Truncate a String not working

Truncate a String not working
0

#1

Tell us what’s happening:

Your code so far


function truncateString(str, num) {
  var newStr= "";
  for(var i=0;i<=str.length;i++){
    var ch = str.charAt(i);

    if(i<num){
      newStr =newStr +ch;

    }else{
      newStr =newStr+"...";

    }
  }
  return newStr;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

You did not ask a question in your post, but I assume you are wondering why you are not passing most of the tests.

If you have not already, I suggest adding a console.log(newStr) before the return statement, so you can see what values your function is returning for each test case.

I already checked your code with a console.log statement and see your function returns the following for the testcase truncateString(“A-tisket a-tasket A green and yellow basket”, 8)

A-tisket............................................................................................................

The reason you are getting all of those extra dots in the above test case is that your else code block (seen below) adds 3 dots onto the end of newStr for every character where i >= num. When i is equal to 8, newStr is equal to ‘A-tiscket’, but since you are iterating i all the way through str.length in your for loop, there are 35 more characters after the letters ‘A-tiscket’, so you add 108 dots (3 x 35) to the end of ‘A-tiscket’.