These are chat archives for camperbot/bonfire-truncate-a-string

14th
Dec 2015
Brett Groff
@groffTECH
Dec 14 2015 00:35
hint
CamperBot
@camperbot
Dec 14 2015 00:35

hint [7/7]

Code Solution:

function truncate(str, num) {
  if (str.length <= num)
    return str;

  if (num <= 3)
    return str.substr(0,num) + "...";

  return str.substr(0,num-3) + "...";
}

Code Explanation:

First we need an if-statement to test if the length of the full string passed in as the first argument already fits within the size limit passed in as the second argument. If so we can just return the string that was passed in.

if (str.length <= num)
  return str;

Then we need to check if the num fits into our special case, where the desired length is less than or equal to three. In this case we will return the string trimmed to our target length, followed by "...". We don't need to worry about the "..." being counted against the length of our output string in this case.

if (num <= 3)
  return str.substr(0,num) + "...";

Finally, we write the return for what happens when neither of the previous if-statements have been true. This call to substr() gives us a string that is 3 less than the target length specified by num, which is done so that we have room to add on the "..." and fit within that target.

return str.substr(0,num-3) + "...";

Credits:

If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @Rafase282 @richyvk @ltegman

NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)

type hint for next hint :pencil: [Contribute at the FCC Wiki]