MESSAGE FOR MOD: This question is about keeping full sentences, the linked questions only consider words.
Take the following example:
// I have a long string that I split into sentences
const input =
"This is the first sentence... This is the second, much longer sentence, with some additional puntuations?! Third sentence with a different length! Just a sentence ending with a number 980. Last but not least, the fourth sentence.";
// I used the following code to split the long string into sentences:
const arr = input.replace(/([.?!])\s*(?=[a-zA-Z0-9])/g, "$1|").split("|");
// we can assume that a sentence from the input array does not exceed this limit
const maxLength = 105;
// TODO: magic happens
/* I'm trying to get an array with the sentences re-joined
by a space, split so that one string does not exceed the limit
[
"This is the first sentence... This is the second, much longer sentence, with some additional puntuations?!",
"Third sentence with a different length! Just a sentence ending with a number 980.",
"Last but not least, the fourth sentence."
]*/
codesandbox: https://codesandbox.io/s/string-array-split-max-chunk-length-bfteuh?file=/index.ts
Im trying to get an array that combines the strings of the initial array with a space but considers that the resulting strings cannot exceed a maximum length. Also the strings have to contain full sentences (you can assume a single sentence won't exceed the limit). Also consider "...", "?!", "???", etc. as possibile sentence endings in the original input string.
How would you go about this? Do I have to use recursion to get some kind of concise code? Is recursion the most elegant solution?
Note: So far I tried a reducer but thought that I would have to use the rest of the array in a recursive function.