After looking at the different solutions, I've decided to take my own approach.
One key observation I made is that if the last word is complete, there should always be a space after it.
Therefore, all you have to do is increase your desired length by +1
. If the 66th character happens to be a space, then the last word before it is complete and you shouldn't remove it. But if it's not a space, then it should be discarded.
In situations where the last character is a space, when you .split()
based on spaces, an empty string will be created as the last element because the final space acts as the point of separation - allowing you to safely .pop()
the last element knowing it's either incomplete or empty.
Example code snippet
// Generate a long string with the entire alphabet
var str = new Array(100).fill('abcdefghijklmnopqrstuvwxyz').join(' ');
// Specify the last character to consider
var len = 65;
// Split the string at the specified length + 1
var words = str.slice(0, len + 1).split(/\s+/);
// Remove the last element, which is either empty or incomplete
words.pop();
// Only full alphabets will be displayed
console.log(words);