13aal - 1 year ago 108
Javascript Question

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

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)`

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

`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;
}
``````

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;
}