Truncating the string algorithm task. please tell me where am i wrong?

function truncateString(str, num) {
  // Clear out that junk in your trunk
  if(str.length <= num)
    return str ;
   var new1;
  if(num<3)
    {
      new1 = (str.substr(0,num) + "...");
    }
 
  new1 = str.slice(0, num-3) + "...";
  return new1;
}

truncateString("A-", 1);

truncateString() is not a inheritance method in js. The method(s) you are looking are slice() or split().
Also, you are trying to call the method inside itself. It would create an infinite loop, unless you are trying to do recursion. This problem doesn’t need recursion.

I could be wrong… but it seems like the second new1 overrides the first…

if(num<3)
{
new1 = (str.substr(0,num) + “…”);
}

new1 = str.slice(0, num-3) + “…”;
return new1;

should that not be else?

EDIT: In fact I think if you do a few else if 's and else 'es you can go with one return line

Note that I’m ignoring that logic of the slice and substr that you are doing. I’m just assuming those are correct.

I’ve edited your post for readability. When you enter a code block into the forum, remember to 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 image button in your editor will add backticks as well.

markdown_Forums

1 Like

Thanks brother. That was the exact mistake i was doing. forgot to write else condition there.

1 Like

virtual high five

goodGood. Always easier for someone else to see it…

1 Like