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

262
Visualizações
Cleaner way to remove 2nd word from string. Currently using split, splice, then join

I have a function to always remove the 2nd word from a sentence.

public cleanMessage(message) {
    let cleanedMessage: any = message.split(' ');
    cleanedMessage.splice(1, 1);
    cleanedMessage = cleanedMessage.join(' ');
    return cleanedMessage;
  }

cleanMessage('Hello there world')
// outputs 'Hello world'

Is there a cleaner way of doing this?

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

0

If you're just looking to shorten it, you can use regex:

(?<=\S)\s\S+ will take out the second word in the string

  • (?<=\S) creates a lookbehind for a word
  • \s\S+ selects a space with a word after it

You can then remove this space + word with:

public cleanMessage(message) {
  return message.replace(/(?<=\S)\s\S+/, '');
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Regexp is indeed shorter and IMO easier to read as long as you use simpler operators.

string.replace(/^(\S+)\s+\S+/, '$1')
^ from beginning of string
(\S+) take and remember non-spaces - 1st word
\s+ followed by spaces
\S+ and another word
$1 replace with remembered first word
about 4 years ago · Juan Pablo Isaza Relatório

0

What you wrote is already pretty much as clean as possible.

You could write it a little shorter maybe like:

public cleanMessage = (message) => message
  .split(' ')
  .filter((word, i) => i !== 1)
  .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