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) => {
var words = text.replace(/[\r\n]+/g, ' ').split(' ')
var lineLength = 0
var output = ''
for (var word of words) {
if (lineLength + word.length >= 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?