10 – Truncate a string.js

Bonfire: Truncate a string

Challenge: http://www.freecodecamp.com/challenges/bonfire-truncate-a-string

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.

Remember to use Read-Search-Ask if you get stuck. Write your own code.

Here are some helpful links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
http://ironion.com/bonfire-truncate-string-solution/
https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/bonfire-truncate-a-string

Solution:

function truncate(str, num) {
  // Clear out that junk in your trunk
  if (str.length<=num) {
    return str;
  } else if (num<=3) {
    return str.slice(0,num) + "...";
  } else {
    return str.slice(0,num-3) + "...";
  }
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

Leave a comment