Truncate a String wrong something in my code

Truncate a String wrong something in my code
0.0 0

#1

What is the problem of my code ?

I could not return to below that:

truncateString(“A-tisket a-tasket A green and yellow basket”, 8) should return “A-tisket…”.
truncateString(“Peter Piper picked a peck of pickled peppers”, 11) should return “Peter Piper…”.

Tell us what’s happening:

Your code so far



function truncateString(str, num){
	if(str.length <= num) {
		return str;
	}else if (num <= 3){
		return str.slice(0, num) + '...';
	} else {
		return str.slice(0, num-3) + '...';
	}
}

// console.log(truncate("A-tisket a-tasket A green and yellow basket", 8));



truncateString("eter Piper picked a peck of pickled peppers", 11);



Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/


#2

Your logic is not right.

The first if looks okay, if the truncate number is less than string size, then return the string itself! right.

But when the truncate size is a valid value, you should go for substring operation without no more checks.

So checking if the number is less then or equal 3 is not right!, same you should not override the slice value(num) by mines 3!

simply:

if(str.length<=num){
return str;
}else{
//now go for it, slice the string with num, and add the 3 dots after it
}

#4

I think that before the change to the new FCC this challenge was a bit different so that any solutions floating around the internet may be outdated. The current version is actually much less complicated.

This solution below does not appear to satisfy the present version of this challenge.
https://forum.freecodecamp.org/t/freecodecamp-algorithm-challenge-guide-truncate-a-string/16089


#5

You misunderstood the specifications. Reread these instructions carefully. There are only 2 possible return statements.

if it is longer than the given maximum string length (second argument). Return the truncated string with a … ending.