简体   繁体   中英

How can I slice a block of text so that it doesn't end on a split word?

I've written code that takes a large block of text, splits it into 995 character blocks and pushes each block into an array. However, this often results splits words when they fall at the 995-character line- how could I edit my code so that each block of text is as close as possible to 995 characters long (must be under) but ends at the last available space?

function cutUp() {
var PAname = prompt("Determine PA type and PA Name (e.g. 5=mexican food=");
var chunks = [];
var OGstring = document.getElementById('PATypes').value;
var my_long_string = OGstring.split('1').join('').split('2').join('').split('3').join('').split('4').join('').split('5').join('').split('6').join('').split('7').join('').split('8').join('').split('9').join('').split('0').join('').split('[edit]').join('').split('[citation needed]').join('').split('[').join('').split(']').join('').split('(').join('').split(')').join('');



var i = 0;
var n = 0;
while (n < my_long_string.length) {
    chunks.push(my_long_string.slice(n, n += 995));

}
if (chunks[0] != null) {
    $('PAType=Name=Value8').innerHTML = PAname + chunks[0];
}
if (chunks[1] != null) {
    $('PAType=Name=Value9').innerHTML = PAname + chunks[1];
}
if (chunks[2] != null) {
    $('PAType=Name=Value10').innerHTML = PAname + chunks[2];
}
if (chunks[3] != null) {
    $('PAType=Name=Value11').innerHTML = PAname + chunks[3];
}
if (chunks[4] != null) {
    $('PAType=Name=Value12').innerHTML = PAname + chunks[4];
}
if (chunks[5] != null) {
    $('PAType=Name=Value13').innerHTML = PAname + chunks[5];
}
if (chunks[6] != null) {
    $('PAType=Name=Value14').innerHTML = PAname + chunks[6];
}
if (chunks[7] != null) {
    $('PAType=Name=Value15').innerHTML = PAname + chunks[7];
}
if (chunks[8] != null) {
    $('PAType=Name=Value16').innerHTML = PAname + chunks[8];
}
if (chunks[9] != null) {
    $('PAType=Name=Value17').innerHTML = PAname + chunks[9];
}

////this is to create new exportable table
$('exportTable').innerHTML += $('tableContents').innerHTML;
$("exportTable").removeClass('hidden');
///this resets to default
defaultReset();

}​

Without any specific Javascript knowledge, I'd say to look ahead 995 characters, and if that character isn't itself a space, to start looking back towards the start until you find a space, and truncate there.

In C-like pseudocode, with chars being your big array of characters:

for(truncOffset = 995; truncOffset > 0; truncOffset--):
{  
    if chars[currentLoc + truncOffset] = ' ': /* a space character */ break;  
}

Rinse, repeat to taste. Remember to move currentLoc to currentLoc + truncOffset after finding that space.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM