How Can I Chunk A String In JavaScript Respecting Words?

- 1 answer

I have a large block of text and I want to split that into an array with each element being one line of up to 50 characters. If the string contains a \r or \n, I want that to be an element itself (not part of another string). I'm a bit perplexed on how to do this.

I've tried

lines = newVal.match(/^(\r\n|.){1,50}\b/g)

I've also tried underscore / lodash _.chunk but that ignores words obviously. But this gives me only the first match. Please help.



Try this:

result = lines.split(/(?=(\r\n))/g);
result.forEach(function(item,index,arr) {
  if(item.length > 50) {
    var more = item.match(/.{1,50}\b/g);
    arr[index] = more[0];
    for(var i=1; i<more.length; ++i) {
      arr.splice(index+i, 0, more[i]);      

This will first split the text into an array by your newlines, then go and further break up the long lines in the array, maintaining the words.