Truncate a String Help Please

Truncate a String Help Please
0

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

  return strSliced.slice(0,-3) + "...";
}

Will someone please tell me what is wrong with this?!

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


#2

For the following test case your function returns “A-tis…” instead of “A-tisket…”

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

For the following test case your function returns “Peter Pi…” instead of “Peter Piper…”

truncateString("Peter Piper picked a peck of pickled peppers", 11)

#3

I don’t know how to make it do that


#4

I added some console.log to your code. If you open your browser console and run the tests you can see what the value of your strSliced variable is at various points in your function.

function truncateString(str, num) {
  // Clear out that junk in your trunk
  if(str.length<=num){
    return str;
  }
  
  var strSliced = str.slice(0,num);
  console.log("sliced string: " + strSliced)

  if(strSliced.length<=3){
    return strSliced + "...";
  }
  
  console.log("sliced string sliced again: " + strSliced.slice(0,-3) + "...")
  return strSliced.slice(0,-3) + "...";
}