Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chunk a string in JavaScript respecting words?

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.

like image 411
Shamoon Avatar asked Feb 09 '23 06:02

Shamoon


2 Answers

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.

like image 175
zpr Avatar answered Feb 10 '23 18:02

zpr


Try using String.prototype.split() , while loop , Array.prototype.some() , Array.prototype.filter() , String.prototype.slice() , Array.prototype.splice()

// call `.split()` of `largeBlockOfText` with `RegExp` `/\r|\n/` 
var arr = largeBlockOfText.split(/\r|\n/);
// while `arr` has element where `.length` greater than `50`
while (arr.some(function(v) {return v.length > 50})) {
  // filter element in `arr` where element has `.length` greater than `50`
  var j = arr.filter(function(val, key) {
    return val.length > 50
  })[0]
  // get index of `j` within `arr`
  , index = arr.indexOf(j)
  // text of `j`
  , text = j
  // index to insert block of 50 characters of `text`
  , i = 1;
  while (text.length) {   
    // insert block of 50 characters from `text` at `index` + 1
    arr.splice(index + i, 0, text.slice(0, 50));
    // reset `text`
    text = text.slice(50, text.length);
    // increment `i` : `index`
    ++i;
  }
  // remove `j` , reset `i`
  arr.splice(index, 1); i = 1;
}
like image 32
guest271314 Avatar answered Feb 10 '23 19:02

guest271314