I have a long string that needs to be sliced into separated chunks inside an array, with a predefined length limit the chunks. Some rules apply:
Example for 25 characters max, you can use this pattern:
/\S[\s\S]{0,23}\S(?=\s|$)/g
demo
code example:
var text = " I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.";
var myRe = /\S[\s\S]{0,23}\S(?=\s|$)/g;
var m;
var result = new Array();
while ((m = myRe.exec(text)) !== null) {
result.push(m[0]);
}
console.log(result);
Note: if you need to choose dynamically the max size, you must use the alternative syntax to define your RegExp object:
var n = 25;
var myRe = new RegExp("\\S[\\s\\S]{0," + (n-2) + "}\\S(?=\\s|$)", "g");
pattern details:
\S # a non-space character (it is obviously preceded by a space
# or the start of the string since the previous match
# ends before a space)
[\s\S]{0,23} # between 0 or 23 characters
\S(?=\s|$) # a non-space character followed by a space or the end of the string