Crop long string using a given limit in JavaScript
Write a program that will crop the long string by using a given limit. For example, if we have a string like this:
‘The quick brown fox jumps over the lazy dog’ and we have the limit 39 then it should return:
‘The quick brown fox jumps over the lazy’
We should consider the following:
1. It should not corp part of the word
2. Output string should not contain space at the end
3. The output string should not exceed the limit
const getCroppedMsg = (message, K) => { if(message.length < 1) { return ''; } const result = []; let word = ''; for(let i =0 ; i < message.length; i++) { if(message[i] === ' ') { result.push(word); word = ''; } else { word += message[i]; } if((i + 1) === message.length && word) { result.push(word); } if((i + 1) === K) { if(message[i + 1] === ' ' && word) { result.push(word); } break; } } return result.join(' '); }; const input = 'The quick brown fox jumps over the lazy dog'; const limit = 39; console.log(getCroppedMsg(input, limit)); // Output: 'The quick brown fox jumps over the lazy'