Truncate a String , someone explain me what is happening here


function truncateString(str, num) {
let string = ""
if(num){
for (let i=0; i<num; i++){
  string += str[i]
}
return string+"...";
}else {
  return string  `// this is not working`
}
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 10));

A-tisket a… //output

Challenge: Truncate a String

Link to the challenge:

The function will always be called with num, so it will never enter the else-code.

Also try calling it with a number bigger than the length of the string and you will notice the first part also isn’t working.

so what to do to solve??

if num what?
when is it that you need to truncate the string?

if the string length is greater than num.

then you need to use that as condition for the if statement

ok but the dots are not going

what’s your code now?

it is working now

if(num<str.length){
    return str.slice(0,num)+"..."
  }else{
    return str
  }
2 Likes

good job!

Happy coding!

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