My goal is to work with a string that is between 2000 and 3000 characters long, containing over a hundred non-uniformly placed \n
characters. I want to divide this string into segments of 1000 characters each. In the resulting array of strings, I want to ensure that each segment ends at the last occurrence of \n
(remaining intact if no \n
is present). Any leftover characters after the last \n
should be added to the beginning of the next segment in the array. This process should happen sequentially for each segment after it has been processed up to the last \n
.
I hope my explanation is clear. Here is the code snippet:
module.exports={
async split(text,length,max){
if (text.length > max){
return;
}
let regex = new RegExp(`.{1,${length}}`, "g");
let splitted = text.match(regex);
return splitted;
}
}
The following section shows how the function is utilized:
let splitted = await split(lyrics,1000,6000)
Although I have successfully split the text every 1000 characters, I am struggling with implementing the functionality described above. Can someone provide assistance?
EDIT: Let's consider an example where we want to split the string into segments of maximum 20 characters, ensuring the total length does not exceed 1000 characters. If the limit is surpassed, nothing will be returned. The secondary splitting operation (as explained in the initial question using \n
) can also use whitespace (
).
For instance, given the string:
Hello, I love Stack Overflow, and it is super cool
let string = `Hello, I love Stack Overflow, and it is super cool`
let splitted = await split(string, 10, 1000)
We currently get:
["Hello, I l", "ove Stack ", "Overflow, ", "and it is ", "super cool"]
If we were to introduce another argument in the split()
function:
async split(text, length, max, splitAt)
Where splitAt
can represent either \n
or
, based on preference.
The desired output would be:
["Hello, I", "love Stack", "Overflow,", "and it is", "super cool"]
I am having trouble figuring out how to achieve this result.