I am currently working on a function to shorten a text if it exceeds a certain length.
For example, calling shorten_text_easy(text, 30)
should output
"We believe. In the future"
.
The initial loop is functioning correctly and showing the total length of the strings in the array accurately. However, I am encountering an error in the second loop and have been unable to pinpoint the issue.
var text = "We believe. In the future. The future is here. This is a test. We are testing.";
function shorten_text_easy(text, number) {
var text_array = text.split('. ').join('.///').split('///'); // Breaking down the text into an array
var text_array_length = text_array.length;
var total_text_array_length = 0; // Initial value set to zero; represents the overall length of all strings in the array
for (var i = 0; i < text_array_length; i++) { // Loop runs while i is less than the array's length
total_text_array_length += text_array[i].length; // Adds up lengths of all strings
}
total_text_array_length = total_text_array_length + text_array_length - 1; // Adjusting for omitted spaces in the array
console.log(total_text_array_length); // Displays the initial total length in the console
for (total_text_array_length; total_text_array_length > number; text_array.pop(-1), text_array_length--) { // Aiming to remove the last item from the array if its total length exceeds 'number'
for (var i = 0; i < text_array_length; i++) {
total_text_array_length += text_array[i].length;
console.log(total_text_array_length);
}
total_text_array_length = total_text_array_length + text_array_length - 1;
}
return text_array // Expected to return the final modified text array when the total string length is within the specified number
};
console.log(
shorten_text_easy(text, 30)
);