Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
How to split a string and then split the returned value again connected to another value that has to be split, and join the remainder to the remaining

What I want is something like a string that is around 2000 to 3000 characters with over a hundred non-uniformly located \n in them, and I want to split them for every 1000 characters, and then in the returned strings in an array, for each of the values in the returned array, I want to end the string at the last \n (leaves it as it is if the string contains no \n) and the remainder of the string after the last \n should be appended to the beginning of the next value in the array, and then this should be carried out AFTER the previous string has been fixed to the last \n

I hope you understand what I mean, and this is my code

module.exports={
    async split(text,length,max){
        if (text.length > max){
            return;
        }
        let regex = new RegExp(`.{1,${length}}`, "g");
        let splitted = text.match(regex);
        return splitted;
    }
}

The place where its fetched and executed is here:

        let splitted = await split(lyrics,1000,6000)

I managed to do the split for every 1000 words but the thing that I explained at the top is what I want to do and I am unable to manage it, so can anyone help out?

EDIT: Suppose I wanted to split the string for a max of 20 characters with the max string length of 1000, and if it bypasses that limit, then it means that nothing will be returned. It can do that second stage of splitting (as I mentioned in the question as \n) with a whitespace ( ). Imagine that the string is: Hello, I love Stack Overflow, and it is super cool In my current code, if we did

let string = `Hello, I love Stack Overflow, and it is super cool`
let splitted = await split(string, 10, 1000)

It would return

["Hello, I l", "ove Stack ", "Overflow, ", "and it is ", "super cool"]

What if another agument is added in split(), making it:

async split(text, length, max, splitAt)

splitAt can mean \n or depending on choice

The result that I want to return is: ["Hello, I", "love Stack", "Overflow,", "and it is", "super cool"]

The thing is, I can not understand how to do it

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If I understand it correctly, you want to split the text into chunks that have a max size of 1000, and they should end with a newline character.

function split(str, chunkSize){
    const chunks = [];
    let current_chunk = ""
    str.split("\n").forEach(part => {
        if(current_chunk.length + part.length > chunkSize){
            // Adds the chunk to chunks and resets current chunk.
            chunks.push(current_chunk);
            current_chunk = "";
        }
        // adds \n to the start of the part, if the current chunk isn't empty.
        current_chunk.length 
           ? current_chunk += `\n${part}`
           : current_chunk += part
    })
    // Used to get the last one, if it isn't empty.
    if(current_chunk.length) chunks.push(current_chunk);
    return chunks;
}

Should look something like this. Haven't tested it though, since I've written it on my phone.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You certainly don't need this method to be async and it should just be a case of stepping through the string, splitting by len and finding the lastIndexOf your splitAt argument, and then taking that chunk into an array using substring

Something like this:

function split(text, len, max, splitAt) {
  if (text.length > max) {
    return;
  }

  let pos = 0;
  const chunks = []
  while (pos < text.length) {
    if (pos + len >= text.length) {
      chunks.push(text.substring(pos));
      pos = text.length
    } else {
      const s = text.substring(pos, pos + len + 1).lastIndexOf(splitAt);
      chunks.push(text.substring(pos, pos + s));
      pos += s + 1;
    }
  }
  return chunks;

}

let string = `Hello, I love Stack Overflow, and it is super cool`
let splitted = split(string, 10, 1000, " ")
console.log(splitted);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda