JSFiddle - React, Tailwind, and code Playground
by emilcieslar
JavaScript
const split = (rawText, chunkLength) => {
const result = [];
let text = rawText;
while (text.length > 0) {
if (text.length > chunkLength) {
let chunk = text.slice(0, chunkLength);
if (chunk[chunk.length - 1] !== ' ') {
// look for space backward
const lastIdxOfSpace = chunk.lastIndexOf(' ');
if (lastIdxOfSpace === -1) {
text = text.slice(chunk.length);
} else {
chunk = text.slice(0, lastIdxOfSpace + 1);
text = text.slice(lastIdxOfSpace + 1);
}
} else {
text = text.slice(chunkLength);
}
result.push(chunk);
} else {
result.push(text);
text = '';
}
}
return result.join('\n');
}