Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript separate string within maximum number

Tags:

javascript

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?

like image 319
user2028856 Avatar asked Dec 14 '25 07:12

user2028856


1 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.

like image 154
eloyra Avatar answered Dec 16 '25 23:12

eloyra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!