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 is splitting words:
var length = shortData.new.length;
if (length < 160){
outputString[0] = shortData.new;
document.write(outputString[0]);
}
if (length > 160 && length < 308){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]);
}
if (length > 308 && length < 468){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]);
}
if (length > 468 && length < 641){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,468);
outputString[3] = shortData.new.substring(468,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]+"(txt4more..)");
document.write(outputString[3]);
}
How to Split a String by Each Character. You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
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."]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With