I've adapted a PHP script lifted from another project to use in JavaScript, this script works great for shortening text to a set limit. I would like to use it to also split it to multiple parts if it is over the set limit.
The current code which shortens once is here: http://jsfiddle.net/WilliamIsted/P5jxK/
Here's what I have so far: http://jsfiddle.net/WilliamIsted/UkhXL/ (I'm pretty sure I'm not doing it right)
I have gotten stuck in loops a few to many times, I'm not sure how to proceed with it.
function strTruncate($string, $your_desired_width) {
arr = [];
if (typeof($last_part)) {
$last_part = 0;
}
$parts = $string.split(/([\s\n\r]+)/);
$parts_count = $parts.length;
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += $parts[$last_part].length;
if ($length > $your_desired_width) {
break;
}
}
$start_part = 0;
return $parts.slice($start_part, $last_part).join('');
}
Shorten Once Result:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae
New Expected Result:
array[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae",
array[1] = "vulputate ante quam ut augue. Praesent sit amet varius lorem. Aliquam odio nunc, mattis in mollis vitae, laoreet non velit. Curabitur"
array[2] = "adipiscing, nisl tincidunt consequat ornare, ligula mauris sed."
.count()with.length. It hurts :-).length()before, obviously that didn't work.