Text-wrapping function in JavaScript I have the following code on my server that takes a string and inserts newlines in such a way that the string is separated into lines, all of which are shorter than maxLineLength in characters. This ensures that the text, when printed, will fit within a certain width.

const formatTextWrap = (text, maxLineLength) =&gt; {
  var words = text.replace(/[\r\n]+/g, ' ').split(' ')
  var lineLength = 0
  var output = ''
  for (var word of words) {
    if (lineLength + word.length &gt;= maxLineLength) {
      output += `\n${word} `
      lineLength = word.length + 1
    } else {
      output += `${word} `
      lineLength += word.length + 1
    }
  }
  return output
}


What optimizations could I make? This code works, but are there any pitfalls to using this?
I would modify a bit logic regarding spacing between words in lines. With your solution you might end up with unnecessary spaces on line ends.

Additionally using Array.reduce instead of for loop is more JS-way to join array. 



const formatTextWrap = (text, maxLineLength) =&gt; {
  const words = text.replace(/[\r\n]+/g, ' ').split(' ');
  let lineLength = 0;
  
  // use functional reduce, instead of for loop 
  return words.reduce((result, word) =&gt; {
    if (lineLength + word.length &gt;= maxLineLength) {
      lineLength = word.length;
      return result + `\n${word}`; // don't add spaces upfront
    } else {
      lineLength += word.length + (result ? 1 : 0);
      return result ? result + ` ${word}` : `${word}`; // add space only when needed
    }
  }, '');
}

let testingText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam blandit mauris id venenatis tincidunt. Vestibulum at gravida sapien. Mauris tellus augue, aliquet sed laoreet blandit, pulvinar sed felis. Phasellus nec est vitae enim blandit facilisis.
Vestibulum fermentum ligula sit amet volutpat fermentum. Sed in faucibus orci. Pellentesque a dui ex. Curabitur sollicitudin, nulla id dignissim lacinia, odio mauris blandit nisi, eget auctor arcu odio nec est.`;
console.log(formatTextWrap(testingText, 20));