Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
How to split a string into a specific number of words and put it together as a single sentence in JavaScript

I need to split a big string into 5 words and return a sentence from these 5 words. Example:


// The string that needs to be split
'Hello, this is a very big string that goes on for loooooooooong'

// The output i need
'Hello, this is a very

I know I can use split(' ', 5) to separate the first 5 words, but i don't know how to put them back together into a sentence. Thanks in advance for your help and i you need me to clearer just ask.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You just need to rejoin the splitted array:

split(' ', 5).join(' ');
about 4 years ago · Juan Pablo Isaza Relatório

0

You can easily achieve the result using split, slice and join and using regex /\s+/

enter image description here

const str = "Hello, this is a very big string that goes on for loooooooooong";

const result = str.split(/\s+/).slice(0, 5).join(" ");
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Using Array.prototype.join() which creates and returns a new string by concatenating all of the elements in an array.

const s = 'Hello, this is a very big string that goes on for loooooooooong';

const str = s.split(' ', 5).join(' ');

console.log(str);

More about Array.prototype.join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda