Truncate a String Alternate Solution(possibly)

I have completed the Truncate a String challenge using the following code. After completing it, I went to the challenge’s guide and did not see anything using substr() like my solution does, and was wondering if my solution is correct, or if it just happens to pass the few tests provided. It seems that my solution, if indeed correct, is much simpler than those using “num-3”, “num>=3” etc.

Your code so far


function truncateString(str, num) {
  if (str.length > num){
return str.substr(0,num) + "...";
  }
  else{
  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/66.0.3359.181 Safari/537.36.

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

1 Like
function truncateString(str, num) {

  let splitStr = str.split("");

  if(num>=str.length)
    return str;

  let newStr="";
  for(let i=0;i<num;i++){
    newStr+=splitStr[i];
  }
  
  return newStr+="...";

}