I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.
Example:
Input String: The quick brown fox jumped over the fence, K: 11
Output: The quick
Here is what I have tried:
function crop(message, K) {
var originalLen = message.length;
if(originalLen<K)
{
return message;
}
else
{
var words = message.split(' '),substr;
for(var i=words.length;i > 0;i--)
{
words.pop();
if(words.join(' ').length<=K)
{
return words.join(' ');
}
}
}
}
This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?