Truncate a String --- HELLPPP

Tell us what’s happening:
I’m not sure why my .substring method isn’t working. Any tips/advice are very much appreciated!

Your code so far


function truncateString(str, num) {
  if (str.length > num)
  return str.substring(0, 3);
}


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

Your browser information:

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

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

No I am trying to truncate it so I get a new string, that’s been truncated, but I am trying to use the substring method, I think I may have forget an else statement

Ok, your right, the .substring method won’t seem to be useful or work for this challenge, I am going to try the slice method

Still trying the slice method

here’s my solution, yet it does not seem to be working.
\\
function truncateString(str, num) {
if (str.length > num){
return str;
}
else
return str.slice(0, 3) + “…”;
}

truncateString(“A-tisket a-tasket A green and yellow basket”, 8);
\\\

Your if statement is wrong … you saying if the string length is greater than cut off point then return string as is, which is wrong. You want to slice it if your string is greater than cutoff point and return it as it is only if its less or equals a cutoff point.

Also as Randell pointed out you want your slice to be num not 3 like following str.slice(0, num);

1 Like