Algorithm Scripting: Truncate a String

Hi,

here is my solution for the “Truncate a String - Challange”.
I tried to make it as simple as possible, but it’s not working, even i got the right console.log answers.
I know there are other solutions out there, but i want to know how i can make my work.

function truncateString(str, num) {
  // Clear out that junk in your trunk

  let word = "";

  word = str.slice(0, num);
  word = '"' + word + '..."';
  console.log(word);

  return word;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);
truncateString("Peter Piper picked a peck of pickled peppers", 11)
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)
truncateString("A-", 1)
truncateString("Absolutely Longer", 2)

console.log


"A-tisket..."
"Peter Piper..."
"A-tisket a-tasket A green and yellow basket..."
"A-tisket a-tasket A green and yellow basket..."
"A..."
"Ab..."

I would suggest to make

this dynamic.

SPOILER ALERT

SOLUTION AHEAD

function truncateString(str, num) {
  // Clear out that junk in your trunk

  let word = "";
  let lastDots = function(a,b) {
    if(a.length>b) {
       return '...';
    }else{
      return '';
    }
  }
  word = str.slice(0, num);
  word = '' + word + lastDots(str,num);
  console.log(word);

  return word;
}

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

I would suggest always running your code in a browser console, look at what you’re actually returning.

Hints

Putting quotes around a block of characters makes them a string (a string literal), putting quotes around data that already is a string does what?

Something else to keep in mind. Run the below in Chrome’s console, observe the different outputs, namely the color coding, and when you see, or don’t see, quotes on strings.

var num = 5;
var str = 'test';
console.log(num);
console.log(str);
str;