JSFiddle - React, Tailwind, and code Playground
by emilcieslar
JavaScript
function chunkString(str, length) {
const stringsArr = [];
let string = str.replace(/(\r\n|\n|\r)/gm, "");
let stringLength = string.length;
let nextChar;
while (string.length > 0) {
let lastCharIndex = length;
const lastChar = string.substring(lastCharIndex - 1, lastCharIndex);
nextChar = string.substring(lastCharIndex, lastCharIndex + 1);
console.log('!!!nextCharOut:' + nextChar)
if (lastChar !== ' ' && !nextChar.match('[^a-zA-Z]')) {
while (!nextChar.match('[^a-zA-Z]') && stringLength >= lastCharIndex) {
lastCharIndex += 1;
nextChar = string.substring(lastCharIndex, lastCharIndex + 1);
console.log('!!!nextCharIn:' + nextChar)
}
}
stringsArr.push(string.substring(0, lastCharIndex));
string = string.substring(lastCharIndex);
stringLength = string.length;
}
return stringsArr;
}
var string = "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."
var splittedStringArr = chunkString(string, 25);
console.log(splittedStringArr.join('\n'));