I have a div let's say with 3 lines of text. I want to split that div into two, so let's say I have 150 characters, I want to split it so I would end up with two equal parts by word.
So let me explain a bit more:
A text node is below... It has 6 lines in the stackoverflow wysiwyg container:
<p>Brown the roast on all sides in a large lightly oiled skillet over high heat, before
adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring
potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length.
Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on
top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover
and cook on low for 8-10 hours. Yield: 6 servings.</p>
Let's say I want to split that div into two divs of 52 pixels (according to my browser it is 104 pixels height). But I want to do it so it doesn't mean up the wording, meaning I don't want to splitCut into two words, so C in one div and ut in another, for example.
So I would end up with something like
Div 1
<p>Brown the roast on all sides in a large lightly oiled skillet over high heat, before
adding to the slow cooker. While meat is browning. Prepare vegetables by washing and paring
potatoes, carrots, and parsnips. Cut into pieces, approximately 2 inches (5 cm) in length. </p>
Div 2
<p>Place in the bottom, and up the sides, of a slow cooker. Add onions, and place pot roast on
top. Combine cranberry sauce, orange juice, rind and cinnamon and pour over the meat. Cover
and cook on low for 8-10 hours. Yield: 6 servings.</p>
Is there a way to do this?
You could use
var text = $('div').text();
var tokens = text.split(' ');
var n = Math.floor(tokens.length/2);
var html = '<p>'+tokens.slice(0, n).join(' ') + '</p><p>' + tokens.slice(n+1, tokens.length).join(' ') + '</p>';
$('div').html(html);
Demonstration
Note that for a better result, especially regarding a recipe, you could also split on the dot :
var text = $('#a').text();
var tokens = text.split('.');
var n = Math.floor(tokens.length/2);
var html = '<p>'+tokens.slice(0, n).join('.') + '.</p><p>' + tokens.slice(n+1, tokens.length).join('.') + '</p>';
$('#a').html(html);
Demonstration with a split on the dot
Now, it's probable you don't want to have the same number of sentences in both paragraph but about the same length in characters. Then, here's what you can do :
var text = $('#a').text();
var sentences = text.split('.');
var sum = 0;
var lengths = sentences.map(function(v){sum+=v.length; return v.length});
var n = 0;
var ts = 0;
while (ts<sum/2) ts += lengths[n++];
var html = '<p>'+sentences.slice(0, n-1).join('.') + '.</p><p>' + sentences.slice(n, sentences.length).join('.') + '</p>';
$('#a').html(html);
Demonstration (not on jsfiddle.net because they seem to be down)
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