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

255
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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