I am trying to take a large block of text and split it into multiple strings that are 148 characters each, while avoiding cutting off words.
I have this now, which
You can use this function, just pass in your string and the length and it will return the array, like:
var outputString = splitter(shortData['new'], 148);
The function:
function splitter(str, l){
var strs = [];
while(str.length > l){
var pos = str.substring(0, l).lastIndexOf(' ');
pos = pos <= 0 ? l : pos;
strs.push(str.substring(0, pos));
var i = str.indexOf(' ', pos)+1;
if(i < pos || i > pos+l)
i = pos;
str = str.substring(i);
}
strs.push(str);
return strs;
}
Example usage:
splitter("This is a string with several characters.\
120 to be precise I want to split it into substrings of length twenty or less.", 20);
Outputs:
["This is a string","with several","characters. 120 to",
"be precise I want","to split it into","substrings of",
"length twenty or","less."]