Truncate a String- Am I using substr properly?

Please advise on what is wrong with the below? I will post my understanding of what I want the code to do:

An empty var named truncatedString is created which will be updated in the subsequent if statement.

If the length of the inputted str is more than the value of num which is another input, the if statement code block is activated.

In this code block, the truncatedString var is assigned the value of the first ‘‘num’’ amount of characters, followed by a …

As represented by

truncatedString = str.substr(1,num) + "...";

Your code so far






function truncateString(str, num) {

 let truncatedString = '';

  if (str.length > num) {



    truncatedString = str.substr(1,num) + "...";

  }

  return truncatedString;
}

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/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

What happens if the string is not longer?
Also, naming child variables the same as their parent function is confusing.

1 Like

Yes I was able to fix this shortly afterwards with the following:

function truncateString(str, num) {
  let tStr = '';

  if (str.length > num) {

tStr = str.substr(0,num) + "...";

return tStr;

  } else {
  return str;
}

}

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

Thank you