I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation.
Any Idea?
We can try a reduce
I do 500 here since your text was < 400
let str = `I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation. I have a text with roughly 1500 - 2000 characters. This text should be split into blocks of text with roughly 400 characters each (does not have to be exactly 400 characters). However it should not just split the text every 400 characters, but split the text only at places where there is a full-stop. So basically divide one big text into several chunks without destroying punctuation.`
let nextPunct = str.indexOf(".")
const lines = str.split(/\.\s+/)
.reduce((acc, line, i) => {
if (i === 0) acc.push(line)
else if ((acc[acc.length - 1].length + line.length) > 500) acc.push(line)
else acc[acc.length - 1] += ". " + line;
return acc
}, [])
const res = lines.join(".\n")
console.log(res, lines.map(line => line.length))