Truncate a String issue with coding

Tell us what’s happening:
Describe your issue in detail here.
The code is giving desired output but I am not able to pass the challenge. There seems to be issue with my code or logic or i fail to understand the instruction. Kindly help me to see the problem.
Thanks.

  **Your code so far**

function truncateString(str, num) {
let trun = '';
if(num > str.length){
  let pivot =  num - str.length;
  num = num - pivot
}
for(let i=0; i<num; i++){
  trun = trun + str[i];
}
trun = trun + '...'
//console.log(trun)
return trun;
}

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length+2);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36

Challenge: Truncate a String

Link to the challenge:

  1. The error messages clearly show where the problems are.
  2. This code has what purpose:
if(num > str.length){
  let pivot =  num - str.length;
  num = num - pivot
}

I use this code when the length of the number is larger than the string because if I don’t cut down the length of the number it outputs “undefined” at the end.

If the number is larger than the string then there is no need to truncate.

If that the case there is a very easy solution for what you can return, since truncation is for the shortening but if you have enough space you don’t need to shorten anything.

When you run the tests and you look at the messages at bottom left, you can see clearly that when num is less than str.length, you are returning what they want you to return but when num is greater than or equal to str.length, you are not returning what they want you to return.

Paste this code just before your return statement:
console.log("test",str,num,trun)
and open developer tools to see your results

Ok,
when num is greater than str, it should not end with ... ending.
Thanks for making me understand and taking time out to help me.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.