I'm having a little problem on splitting my array based on user input. I have a text area in which a user will input an essay and an input box where one can input a number that will be a basis of the split. Supposed the user input "3", the whole essay will be divided into 3 sentences per paragraph.
I have this html thus far,
<textarea id="essay"></textarea>
<input type="text" onkeypress="return show_paragraph(event)" id="input" />
<div id="questionDiv"></div>
and one function that does it all. But the slice only works on the first paragraph, meaning, if i input an essay consisting of 8 sentences and i want to slice it in every 3 sentences for example, i only get two paragraphs, the first one having 3 sentences and the second with 5 sentences when i should have 3 paragraphs with, 3-3-2 sentences..
function show_paragraph(e){
var numSentences = $("#input").val();
var essay= $("#essay").val();
if (e.keyCode == 13 || e.which == 13) {
var sentence_list = essay.split(". "); //array of sentences
var sentence_results = "";
var i,j,paragraph;
var chunk = numSentences;
for (i=0,j=sentence_list.length; i<j; i+=chunk) {
paragraph = sentence_list.slice(i,i+chunk);
sentence_results += '<div id="sentenceDiv" >';
sentence_results += '<h4 id="paragraph'+i+'">'+paragraph+'</h4>';
sentence_results += '</div>';
}
$("#questionDiv").html(sentence_results);
return false;
}
}
And I can't seem to return the period (.) back for each sentences.
Thanks for the help.. =)
Very interesting. Your logic is correct, you only have to fix this 2 lines:
Instead of
var chunk = numSentences;
Do:
var chunk = parseInt(numSentences, 10);
If not, when doing '+' in your for, it will concatenate instead of adding.
And instead of:
paragraph = sentence_list.slice(i,i+chunk);
Do:
paragraph = sentence_list.slice(i,i+chunk).join(". ");
So you get the periods back.
Tested, it works :).
Cheers, from La Paz, Bolivia
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.