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/

When you say “not working” what do you mean? What are you expecting the return statement to do?

If the length of str is greater than num, you are returning the first 3 characters of str. Is that what you want to do?

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

You can assign the results of substring(0, 3) to another variable if you want to do something else with it, but I am not sure how that is going to help you solve this challenge.

var str = '123456789';
var firstThreeChars = str.substring(0, 3); // assigns '123' to firstThreeChars

If you want a new string which has the remaining part after the first 3 characters, you would need to write something like:

var str = '123456789';
var afterFirstThreeChars = str.substring(3); // assigns '456789' to afterFirstThreeChars

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 use of slice here is really the same as what you were doing with substring. If str.length is <= num, you are returning the first 3 characters of the string concatenated with .... You can use substring or slice, but according to the instructions you need to capture all the characters up to the max length specified by num. Nowhere in the instructions does it say to only take the first 3 characters and add ... to it. For example, if num is 7 and str’s length is 9, then you will want to return the first 7 characters of str plus ....

1 Like

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