Message from JavaScript discussions

July 2017

— IDK what they are thinking but... not going to look a gift horse in the mouth haha

— 

I made it better because I was bored:

function wordWrap(input, maxLen) {

  if (!input || input.length <= maxLen) return input;

  var wordsRegex = '.{1,' + maxLen + '}(\\s|$)|\\S+?(\\s|$)';

  var words = input.match(RegExp(wordsRegex, 'g'));

  return words.map(word => word.trim()).join("\n");

}

— I think I can optimize the regex too

— Are you really sure you need the regex though?

— Isn't this a simple split on space and rejoin until under or at specified length?

— The other solution is an 80 line character counting loop

— No

— Has to keep words intact

— 

function wordWrap(input, maxLen) {
const words = input.split(' ');
const lines = [];
let line = [];
words.forEach(word =>
while(line.join(' ').length <= maxLen) {
line.push(word);
}
lines.push(line);
line = [ line.shift() ];
});
return lines.map(line => line.join(' ')).join('\n');
}

Message permanent page

— Something like that?

— I guess you could get rid of the .shift by using a do..while instead

— Why avoid regex though