Truncate a String Challenge

Tell us what’s happening:
Hey guys,
I have passed the challenge but i wish to know alternative approaches to it.
Thanks in advance.

Your code so far


function truncateString(str, num) {
  // Clear out that junk in your trunk
  var dot  = "...";
  if(num >= str.length){
    return str.slice(0,str.length);
  }
  else {
    return str.slice(0, num) + dot;
  }
}

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

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.84 Safari/537.36.

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

This could be useful :

function truncateString(str, num) {
  // Clear out that junk in your trunk
  return num < str.length ? str.slice(0,num)+"..." : str;
}
1 Like

Hey @alpino,
Thanks for reply.