const wordWrap = (str, maxWidth) => {
let lines = str.trim().split(" "),
words = [],
lineLength = 0;
lines.forEach((line) => {
// Add the word to the current line
let wordLength = line.length;
// If the total line length is larger than the max width
if (lineLength + wordLength > maxWidth) {
// Start the new line
lineLength = wordLength;
words.push(line);
}
else {
// Add the word to the current line
lineLength += wordLength + 1;
words[words.length - 1] += " " + line;
}
});
return words.join("\n");
}
使用方式:
let str = "The quick brown fox jumps over the lazy dog";
let wrappedStr = wordWrap(str, 15);
console.log(wrappedStr);
输出:
The quick
brown fox
jumps over
the lazy
dog