So I am having some issues with this exercise. It meets three out of the six requirements to pass. I am doing my best to not look at the solution. Here is the exercise:
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.
It runs these tests:
I am passing the first two and the last test with my code.
Tests
Passed:truncateString(“A-tisket a-tasket A green and yellow basket”, 8) should return the string A-tisket…
Passed:truncateString(“Peter Piper picked a peck of pickled peppers”, 11) should return the string Peter Piper…
Failed:truncateString(“A-tisket a-tasket A green and yellow basket”, “A-tisket a-tasket A green and yellow basket”.length) should return the string A-tisket a-tasket A green and yellow basket.
Failed:truncateString(“A-tisket a-tasket A green and yellow basket”, “A-tisket a-tasket A green and yellow basket”.length + 2) should return the string A-tisket a-tasket A green and yellow basket.
Failed:truncateString(“A-”, 1) should return the string A…
Passed:truncateString(“Absolutely Longer”, 2) should return the string Ab…
Here is my code:
function truncateString(str, num) {
let newStr = '';
for (let i = 0; i < str.length; i++) {
if (str[i].length < num) {
newStr = str.slice(str[i], num) + "...";
}
}
return newStr;
}
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));
console.log(truncateString("Peter Piper picked a peck of pickled peppers", 11));
Can anyone help me figure out where I am going wrong?