JSFiddle - React, Tailwind, and code Playground
by emilcieslar
JavaScript
function splitText(str, n) {
// remove line breaks
str = str.replace(/(\r\n|\n|\r)/gm, " ");
let output = [];
let arr = str.split(" ");
let last = 0;
while (last < arr.length) {
let line = "";
for (i = last; line.length < n; i++) {
line += arr[i] + ' ';
last++;
}
// remove spaces at the end of line
line = line.trim();
// if the line is longer than n: remove last word
if (line.length > n) {
let lastIndex = line.lastIndexOf(" ");
line = line.substring(0, lastIndex);
last = last - 1;
}
output.push(line);
}
return output;
}
var array = splitText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", 25);
console.log(array.join('\n'));