Heggy Castaneda
Jul 28, 2017 · 3 min read

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

However, if the given maximum string length max 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.

(note: I change num argument to max. It makes more sense to me since maximum string length represents num)

// starter code
function truncateString(str, max) {

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

Break down of the word problem into something I can digest.

// string.length is longer than max, max > 3, 
Note that inserting the three dots to the end will add to the string length therefore take out 3 from max number when slicing. This is most normal case when truncating is happening
Case1) if ( string.length > max && max >3 ) {
slice(startCopyIndex, max - 3 /* EndCopyIndexNotincluded */)
}
// string.length is longer than max, max <= 3
Case2) else if ( string.length > max && max <= 3)
slice(startCopyIndex, max /* EndCopyIndexNotincluded */)
}
// string.length is less than or equal to max
Case3) just return the original string

Review) .slice() method: Remember .slice()’s end Index is NOT included. It returns the copy of new array as return value when running .slice() method. Therefore, setting .slice() to a variable is not necessary (optional). You can simply return its result.


var str = "A-tisket a-tasket A green and yellow basket";
// .slice(start, end index) end index is NOT included
// max length 3, we enter 3 and newStr.length is 3 since
// endIndex is not included in slice
var newStr = str.slice(0,3); //"A-t"
newStr.length === 3; // true

function truncateString(str, max) {
// case1) string length > max and max is longer than 3
if ( str.length > max && max > 3) {
// str.slice returns copy of array (start, endNotIncl), concat ...
return str.slice(0, max - 3) + "...";
// case2) string length > max and max less than equal to 3
// if max is less or equal to 3 then do not add ... to string length.
// Don't take out -3 from max number when slicing array
} else if ( str.length > max && max <= 3) {
return str.slice(0, max) + "...";
// case3) string length is less than max therefore no need truncate
} else {
// simply return str
return str;
}
}
debugger;
truncateString("A-tisket a-tasket A green and yellow basket", 11);
Credit: chingu-voyage Chance Taken
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade