My solution to FreeCodeCamp bonfire 11 Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a "..." ending.
Note that the three dots at the end add to the string length.
If the num is less than or equal to 3, then the length of the three dots is not added to the string length.
function truncate(str, num) {
// Clear out that junk in your trunk
//If the num is less than or equal to 3, then the length of the three dots is not added to the string length.
if (num <= 3)
return str.slice(str, num) + "...";
//Truncate a string if it is longer than the given maximum string length
else if(str.length > num)
return str.slice(str, num-3) + "...";
else if (str.length <= num)
return str;
}
truncate("A-", 1);