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

114
Vistas
I need to filter hyphen(-) and space(" ") in my string, what am I doing wrong?

This is the code I am using (but it only works for hyphens not for spaces)

console.log(
    "some - text".replace(/\s\-/g, '').toLowerCase()
)

Can anyone point out what is wrong in this RegEx ?

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

0

The regex you have removes the space and the dash, leaving the second space

You need other regex to remove all spaces

console.log(
    "some - text".replace(/\s\-/g, '') // space and dash
)

console.log(
    "some - text".replace(/\s-\s/g, '') // space before and after a dash
)


console.log(
    "some     -        text".replace(/\s+\-\s+/g, '') // any whitespace before and after
)


console.log(
    "so- me     -        te-xt".replace(/\s|-/g, '') // all spaces and all dashes, can be written as a acharacter class [\s-]
)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use\W for non-word character:

console.log("some - text".replace(/\W/g, '').toLowerCase())
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your regex is matching "(1 occurrence of some space)(definitely followed by 1 occurrence of ad ash)". You want it to match any occurrence of those, so use a character class in your regex (see: MDN WebDocs: JavaScript Character Classes, with brackets, /[\s\-]/g, like so:

console.log(
    "some - text".replace(/[\s-]/g, '').toLowerCase()
)

Want to replace another character? Just throw it into the class and you're good to go.

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