# Truncate a String - Whats the deal?

So I just solved this algorithm…

Thanks to the error messages that pop up during testing.

This is what I don’t get:

Here are the instructions:

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.

What I don’t get is this… I solved the algorithm by adding 3 dots AFTER truncating the string in all scenarios. This means that whether the dots were included had nothing to do with it the length of the truncation. The only difference is, in the case where num was greater than 3, I did num -3 before truncating the string by num. But still, the dots were never involved in any truncation or in any actual string that was being acted upon by the slice() function, which is why the instructions make no sense to me.

See successful passing code:

``````if (num <= 3){
return str.slice(0, num) + '...';
}
else{
if(num >= str.length){
return str;
}
num = num -3;
return str.slice(0, num) + '...';
}``````
1 Like

When you do `num = num -3;` you account for the dots in your trunction which you are not doing when `num <= 3` so if you believe it or not. The dots are involved when truncating in your algorithm.

Oh I see, so basically, the dots are by default included and we have to remove them when we do the -3 for that particular case…

Good post @TheOnlyRealTodd

I hope my code helps some of you guys to understand the question and solution better. Good luck

``````function truncateString(str, num) {
// Slice 'str' upto the given length
res = str.slice(0, num);
// If 'num' (max-length) is <=3 then, append '...'
if (num <= 3) {
return res+"...";
}
// If 'str' length is less than 'num' then, return 'str' as it is
else if (str.length <= num) {
return str;
}
// If 'str' length is greater than 'num' then slice the string upto max-length and 3 more characters to accomodate '...'
else if (str.length > num) {
return res.slice(0, res.length-3) + "...";
}
}
``````
1 Like

My Solution-

``````function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length<=num){
return str;
}

var strSliced = str.slice(0,num);

if(strSliced.length<=3){
return strSliced + "...";
}

return strSliced.slice(0,-3) + "...";
}