Search code examples
javascripttruncate

Truncating a string in Javascript, confusion of last two test strings


I'm working on a project for freecodecamp.

Rules of the project:

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 inserting the three dots to the end will add to the string length.

However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.

My test strings include:

truncateString("A-tisket a-tasket A green and yellow basket", 11) should return "A-tisket...".

truncateString("Peter Piper picked a peck of pickled peppers", 14) should return "Peter Piper...".

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) should return "A-tisket a-tasket A green and yellow basket".

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return "A-tisket a-tasket A green and yellow basket".

truncateString("A-", 1) should return "A...".

truncateString("Absolutely Longer", 2) should return "Ab...".

Now I've gotten most of this figured out using a ternary operator, so it's fairly simple, except the last two ('A-', 1) and ('Absolutely Longer', 2), my question being, how can I accomplish the truncating successfully and return the expected output of the last two strings?

Source:

function truncateString(str, num) {
  return str.length > num ? str.slice(0, num - 3) + '...' : str;
}

Solution

  • You need to handle the case where num is less than or equal to 3. You can just add another condition to do this:

    function truncateString(str, num) {
      return str.length > num ? str.slice(0, num >= 3 ? num - 3 : num) + '...' : str;
    }
    
    console.log(truncateString("A-tisket a-tasket A green and yellow basket", 11));
    console.log(truncateString("Peter Piper picked a peck of pickled peppers", 14));
    console.log(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length));
    console.log(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2));
    console.log(truncateString("A-", 1));
    console.log(truncateString("Absolutely Longer", 2));