How to divide strings into equal parts

Asked

Viewed 279 times

4

How to divide a texto with or more than 20,000 characters in equal parts and each part containing 5000 characters? (Nodejs)

I have that function:

textBreak = (data) => {
  const characterCounter = data.text.length;
  const pagesCounter = data.numpages;
  var text = data.text;
  var math = Math.round(characterCounter / pagesCounter) + 3000;
  var index = 0;
  var array = [];
  while (index < characterCounter) {
    array.push(text.substr(math, Math.min(index + math, text.length)));
    index += math;
  }
  console.log('textBreak: sucess');
  return { array, pagesCounter, characterCounter, math }
}
module.exports = textBreak;
  • What you’ve done so far? Edith the question and add a [mcve] showing how you tried to solve the problem so we can give you guidance on what you have already done.

  • @Augustovasques ready

  • But you want to break into 5000 fixed or as per data.numpages?

  • Yes, fixed. This function n ta good, I think I don’t even need the numpages, I was just making a calculation to get an idea.

2 answers

3

What you’re looking for is the function that was declared here:

https://stackoverflow.com/questions/7033639/split-large-string-in-n-size-chunks-in-javascript

function chunkString(str, length) {
    return str.match(new RegExp('.{1,' + length + '}', 'g'));
}

If you prefer to use as a polyfill (as is my case) you can use the code below (it needs to run before initializing anything, after all it is a polyfill):

(window => {
    if (!('chunk' in String)) String.prototype.chunk = function(length) {
        return this.match(new RegExp(`.{1,${length}}`, 'g'))
    }
})(window)

When adding polyfill, now simply call the function in any string field, like this:

console.log('12345678'.chunk(2))
// result: (4) ["12", "34", "56", "78"]

2


A possible solution would be to make a while in the string according to its size (length) and within the while, you go break the string with substring, taking a chunk of it and adding it to an array, so the string decreases as the array takes new positions.

function breakString(string, size) {
  //Valor default de 5000
  size = size || 5000;

  let breakStr = [];

  while (string.length > 0) {
    breakStr.push(string.substring(0,size));
    string = string.substring(size,string.length);
  }

  return breakStr;
}

let bigString = "abcdefghij".repeat(2000);

//Quebrar com o tamanho padrão de  5000
console.log(breakString(bigString));

//Quebrar de 130 em 130...
console.log(breakString(bigString, 130));

//Exemplo para verificar se a string de entrada é a mesma de saída
console.log( bigString == breakString(bigString, 147).reduce( (acc, value) => acc += value , "") );

  • I tried to do an async function to take each position of the breakStr array and add a comment at the beginning of the line, like 'Block 1', but I couldn’t. You could help me?

  • Type "Block 1 - abcdefg"?

  • Actually I asked the wrong question, I want that before adding in the breakStr array, each block of the loop added in the array has a tag, Type, The string is "abcdefg" and for example "abc" is a block, it would look like "Block 1: abc", so I thought async/await. Do you understand? I’ve been at this for 3 days :v

  • 1

    If I understood it, it would look like this: https://repl.it/repls/AchingRemorsefulOffices or https://repl.it/repls/VirtualLightyellowProgramminglanguages

  • Aaaa exact, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.