Javascript separate string within maximum number

Viewed 57

I have a long paragraph of text which I need to split this into 30 individual sentences in an array. Using this method only results in individual sentences which are 30 characters long:

var string = 'Sedutperspiciatisundeomnisistenatuserrorsitvoluptatemaccusantiumdoloremquelaudantium,totamremaperiam,eaqueipsaquaeabilloinventoreveritatisetquasiarchitectobeataevitaedictasuntexplicabo.Nemoenimipsamvoluptatemquiavoluptassitaspernaturautoditautfugit,sedquiaconsequunturmagnidoloreseosquirationevoluptatemsequinesciunt.Nequeporroquisquamest,quidoloremipsumquiadolorsitamet,consectetur,adipiscivelit,sedquianonnumquameiusmoditemporainciduntutlaboreetdoloremagnamaliquamquaeratvoluptatem.Utenimadminimaveniam,quisnostrumexercitationemullamcorporissuscipitlaboriosam,nisiutaliquidexeacommodiconsequatur';
var regex = new RegExp('.{1,30}', 'g');
var text_array = string.match(regex);

console.log(text_array);

Is there a way to split the string into a designated number of rows in an array?

3 Answers

You can take the string length and divide it by 30. That way you know how many characters you need to take for each fragment.

var chunks          = Math.ceil(string.length / 30);
var regex           = new RegExp(`.{1,${chunks}}`, 'g');                       
var text_array      = string.match(regex);

Note that you should check for edge cases like a string being less than 30 characters long. And resolve better than with Math.ceil cases where the division isn't exact.

If you have a 62 character long string, Math.ceil(62 / 30) === 3, but 3 * 30 > 62 meaning you can't just take chunks 3 characters long, this is just an illustrative example following your approach.

you can use this function that would return the finalArr with each character of length 30

function splitCharacters(text) {
    if(text && text.length === 0) {
        return [];
    }
    const finalArr = [];
    let value = '';
    for(let i=0;i<text.length;i++){
        if(i%30 === 0 && i) {
            finalArr.push(value);
            value = '';
        }
        value += text[i];
    }
return finalArr;
}

How about a function like pieces that divides the total length by the desired number of pieces...

var string = 'Sedutperspiciatisundeomnisistenatuserrorsitvoluptatemaccusantiumdoloremquelaudantium,totamremaperiam,eaqueipsaquaeabilloinventoreveritatisetquasiarchitectobeataevitaedictasuntexplicabo.Nemoenimipsamvoluptatemquiavoluptassitaspernaturautoditautfugit,sedquiaconsequunturmagnidoloreseosquirationevoluptatemsequinesciunt.Nequeporroquisquamest,quidoloremipsumquiadolorsitamet,consectetur,adipiscivelit,sedquianonnumquameiusmoditemporainciduntutlaboreetdoloremagnamaliquamquaeratvoluptatem.Utenimadminimaveniam,quisnostrumexercitationemullamcorporissuscipitlaboriosam,nisiutaliquidexeacommodiconsequatur';

const testResult = pieces(string, 30);
console.log(testResult.length + " pieces:");
console.log(testResult);


function pieces(str, numPieces){
  const
    len = Math.ceil(str.length/numPieces),
    arr = [];
  while(str.length > 0){
    arr.push(str.slice(0, len));
    str = str.slice(len);    
  }
  return arr;
}

Related