I'm trying to create a robust function that receives a string -- typically a paragraph or two -- and the max number of characters in the output. One condition is to make sure that we return full words and never cut one in half.
Here's the code I have and I feel it needs to be improved. This is normal ES2015/ES6 with no additional libraries.
export const shortenTextToSpecifiedNumberOfCharacters = (input, numberOfCharacters) => { if (!input) return ""; else if (input.length <= numberOfCharacters) return input; for (var i = numberOfCharacters; i > 0; i--) { if (input[i] == ' ') { return input.slice(0, i) + ' ...'; } } } UPDATE: If I'm following the instructions correctly, the final function would look like this:
export const shortenTextToSpecifiedNumberOfCharacters(input, numberOfCharacters) { if (!input) return ""; else if (input.length <= numberOfCharacters) return input; const spaces = " \t\r\n"; for (let i = numberOfCharacters; i > 1; i--) { if (spaces.indexOf(input[i]) >= 0 && spaces.indexOf(input[i-1]) < 0) { return input.slice(0, i) + ' ...'; } else { return input.slice(0,numberOfCharacters); } } }